Ava*_*esh 54
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')
Run Code Online (Sandbox Code Playgroud)
Nad*_*mli 25
我建议你使用Gmail原子Feed
这很简单:
import urllib
url = 'https://mail.google.com/mail/feed/atom/'
opener = urllib.FancyURLopener()
f = opener.open(url)
feed = f.read()
Run Code Online (Sandbox Code Playgroud)
然后,您可以在这篇精彩文章中使用Feed解析功能:以pythonic方式检查Gmail
Mat*_*hen 24
好吧,我将继续按照Cletus的建议拼出一个imaplib解决方案.我不明白为什么人们觉得需要使用gmail.py或Atom.这种事情是IMAP的设计目标.Gmail.py特别令人震惊,因为它实际上解析了Gmail的HTML.对于某些事情可能是必要的,但不是为了获得消息计数!
import imaplib, re
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login(username, password)
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
Run Code Online (Sandbox Code Playgroud)
预编译正则表达式可能会略微提高性能.
小智 7
要从原子提取中读取值的完整实现:
import urllib2
import base64
from xml.dom.minidom import parse
def gmail_unread_count(user, password):
"""
Takes a Gmail user name and password and returns the unread
messages count as an integer.
"""
# Build the authentication string
b64auth = base64.encodestring("%s:%s" % (user, password))
auth = "Basic " + b64auth
# Build the request
req = urllib2.Request("https://mail.google.com/mail/feed/atom/")
req.add_header("Authorization", auth)
handle = urllib2.urlopen(req)
# Build an XML dom tree of the feed
dom = parse(handle)
handle.close()
# Get the "fullcount" xml object
count_obj = dom.getElementsByTagName("fullcount")[0]
# get its text and convert it to an integer
return int(count_obj.firstChild.wholeText)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27134 次 |
| 最近记录: |