web-dev-qa-db-ja.com

Python

短いPythonスクリプトで受信トレイ内の未読のGmailメッセージの数を確認するにはどうすればよいですか?ファイルからパスワードを取得することのボーナスポイント。

34
Steven Hepting
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')
54
Avadhesh

Gmail atom feed を使用することをお勧めします

それはこれと同じくらい簡単です:

import urllib

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

次に、この素​​敵な記事でフィード解析関数を使用できます: GmailをPythonで確認

25
Nadia Alramli

さて、私は先に進み、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)

正規表現をプリコンパイルすると、パフォーマンスがわずかに向上する場合があります。

24

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)
7
PaulF

まあ、それはコードスニペットではありませんが、 imaplibGmail IMAPの指示 を使用すると、ほとんどの方法が得られます。

6
cletus

ログインしたら(手動で、またはgmail.pyを使用して)、フィードを使用する必要があります。

ここにあります: http://mail.google.com/mail/feed/atom

それはGoogleがそれをする方法です。ここにそれらのjsへのリンクがありますchrome extension: 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
Unknown