短い Python スクリプトを使用して、受信トレイ内の未読の Gmail メッセージの数を確認するにはどうすればよいですか? ファイルからパスワードを取得するためのボーナス ポイント。
7 に答える
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')
Gmail アトム フィードを使用することをお勧めします
これは次のように簡単です。
import urllib
url = 'https://mail.google.com/mail/feed/atom/'
opener = urllib.FancyURLopener()
f = opener.open(url)
feed = f.read()
次に、この素晴らしい記事のフィード解析関数を使用できます: Check Gmail the pythonic way
さて、クレタスが提案したように、先に進んで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)
正規表現をプリコンパイルすると、パフォーマンスがわずかに向上する場合があります。
Atom フィードから値を読み取る完全な実装の場合:
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)
これはコード スニペットではありませんが、imaplibとGmail の IMAP の手順を使用すると、ほとんどの場合、そこに到達できると思います。
ログインしたら (手動または gmail.py を使用して)、フィードを使用する必要があります。
ここにあります: 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 yourmail@gmail.com</title>
<tagline>New messages in your Gmail Inbox</tagline>
<fullcount>142</fullcount>
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
ログイン名とパスワードが別の行にあると仮定して、テキスト ファイルからログイン情報を取得します。