使用Python检查未读的Gmail邮件数量

Ste*_*ing 34 python email gmail pop3

如何使用简短的Python脚本检查收件箱中未读Gmail邮件的数量?用于从文件中检索密码的加分点.

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)

  • 我非常喜欢这个解决方案.一般只用一次导入清洁.得到你想要的数字:len(obj.search(无,'UnSeen')[1] [0] .split()) (5认同)

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

  • IMAP有什么坏处?请注意,此代码段不完整,尽管"这样简单". (3认同)
  • 它始终为我发送未经授权的文件"/opt/python2.7/lib/python2.7/urllib.py",第379行,在http_error_default中引发IOError,('http error',errcode,errmsg,headers)IOError:(' http错误',401,'未授权',<httplib.HTTPMessage实例位于0x126cc68>) (3认同)
  • +1精彩的解决方案,避免所有的imap/pop业务! (2认同)

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)

预编译正则表达式可能会略微提高性能.

  • 汤姆,这是真的.但OP没有说他们正在处理这些限制,所以我们不应该过早发明它们. (9认同)

小智 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)


cle*_*tus 6

好吧,它不是代码片段,但我想使用imaplib,Gmail IMAP指令可以帮助您完成大部分工作.