Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python检查Gmail邮件的未读计数_Python_Email_Gmail_Imap - Fatal编程技术网

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

用Python检查Gmail邮件的未读计数,python,email,gmail,imap,Python,Email,Gmail,Imap,如何用一个简短的Python脚本检查收件箱中未读Gmail邮件的数量?从文件中检索密码的额外积分。好吧,这不是一个代码片段,但我想使用它可以让您在最短的时间内到达那里。使用 从文本文件中获取登录信息,假定登录名和密码在单独的行中。我建议您使用 就这么简单: import urllib url = 'https://mail.google.com/mail/feed/atom/' opener = urllib.FancyURLopener() f = opener.open(url) feed

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

好吧,这不是一个代码片段,但我想使用它可以让您在最短的时间内到达那里。

使用

从文本文件中获取登录信息,假定登录名和密码在单独的行中。

我建议您使用

就这么简单:

import urllib

url = 'https://mail.google.com/mail/feed/atom/'
opener = urllib.FancyURLopener()
f = opener.open(url)
feed = f.read()
然后,您可以在本文中使用提要解析功能:

一旦您登录(手动或使用gmail.py执行此操作),您应该使用提要

它位于这里:

谷歌就是这样做的。以下是他们的js chrome扩展的链接:

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

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

Gmail-电子邮件收件箱yourmail@gmail.com
Gmail收件箱中的新邮件
142

好吧,我将继续按照克莱特斯的建议,详细说明一个imaplib解决方案。我不明白为什么人们觉得有必要使用gmail.py或Atom来实现这一点。这就是IMAP设计的目的。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)

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

要完整实现从atom提要读取值,请执行以下操作:

import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')
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)

我检查了模块源代码,它做了什么,它以html模式打开gmail并解析页面。这太糟糕了!readline包含一个尾随的换行符,这在这里是不需要的。Nadia是对的。这将浪费大量的时间和带宽。gmail.py(幸运的)已经不存在了。IMAP有什么不好?请注意,尽管“如此简单”,但此代码段并不完整。还请注意,此解决方案将提示用户在TTY上输入用户名、密码。但是,您可以对opener进行子类化以处理此问题。它总是返回unauthorized for me文件“/opt/python2.7/lib/python2.7/urllib.py”,第379行,在http_error_default raise IOError,('http error',errcode,errmsg,headers)IOError:('http error',401,'unauthorized',)而我恰好同意IMAP是解决此问题的方法,可能会出现一些可移植性问题。由于其他方法都使用HTTP连接,所以当IMAP不使用时(在限制性环境中,如Google App Engine或在非HTTP流量受到限制的网络上),它们可以工作。但是OP没有说他们正在处理这些限制,所以我们不应该过早地发明它们。我真的很喜欢这个解决方案。通常只需一次导入即可清洁。要获取号码,您只需:len(obj.search(None,'UnSeen')[1][0].split())我可以使用此解决方案获取邮件正文和主题吗?@datagrade:通过搜索,您只能获取邮件id,但您可以将其与“obj.fetch(…”一起使用)获取你想要的邮件。查看此链接了解如何实现:使用此链接,我收到通知,有人刚刚使用我的密码尝试使用不安全的应用程序登录,并带有此文档的链接:对于那些对使用imaplib连接gmail感兴趣的人,google将定期禁用第三方访问,您必须手动启用最好创建一个应用程序并使用gmail api。
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)