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

问题描述 投票:34回答:7

如何使用简短的Python脚本检查收件箱中未读Gmail邮件的数量?从文件中检索密码的奖励积分。

python email gmail imap
7个回答
54
投票
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')

25
投票

我建议您使用Gmail atom feed

就这么简单:

import urllib

url = 'https://mail.google.com/mail/feed/atom/'
opener = urllib.FancyURLopener()
f = opener.open(url)
feed = f.read()

然后您可以在这篇不错的文章中使用feed解析功能:Check Gmail the pythonic way


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)

预编译正则表达式可能会稍微改善性能。


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)

6
投票

嗯,这不是代码段,但我想使用imaplibGmail IMAP instructions可以使您获得大部分收益。


1
投票

一旦登录(手动或通过gmail.py进行登录,就应该使用feed。

它位于这里:http://mail.google.com/mail/feed/atom

这是Google的方法。这是他们的js chrome扩展的链接:http://dev.chromium.org/developers/design-documents/extensions/samples/gmail.zip

您将能够解析如下所示的xml:

<?xml version="1.0" encoding="UTF-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<title>Gmail - Inbox for [email protected]</title>
<tagline>New messages in your Gmail Inbox</tagline>
<fullcount>142</fullcount>

-1
投票

使用Gmail.py

file = open("filename","r")
usr = file.readline()
pwd = file.readline()
gmail = GmailClient()
gmail.login(usr, pwd)
unreadMail = gmail.get_inbox_conversations(is_unread=True)
print unreadMail

假设登录名和密码位于单独的行,则从文本文件获取登录信息。

© www.soinside.com 2019 - 2024. All rights reserved.