GMail からメールを取得するために Python imaplib (Python 2.6) を使用しています。メソッドhttp://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetchでメールを取得するすべてのメールを取得します。ダウンロードせずに、テキスト部分だけが必要で、添付ファイルの名前も解析します。これはどのように行うことができますか?GMail から返された電子メールは、ブラウザが HTTP サーバーに送信するのと同じ形式に従っていることがわかりました。
9521 次
3 に答える
5
このレシピを見てみましょう: http://code.activestate.com/recipes/498189/
差出人、件名、日付、添付ファイルの名前、およびメッセージ本文を出力するように少し調整しました (今のところプレーンテキストです。html メッセージを追加するのは簡単です)。
この場合、Gmail pop3 サーバーを使用しましたが、IMAP でも機能するはずです。
import poplib, email, string
mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:YOURUSERNAME') #use 'recent mode'
mailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!
numMessages = len(mailserver.list()[1])
for i in reversed(range(numMessages)):
message = ""
msg = mailserver.retr(i+1)
str = string.join(msg[1], "\n")
mail = email.message_from_string(str)
message += "From: " + mail["From"] + "\n"
message += "Subject: " + mail["Subject"] + "\n"
message += "Date: " + mail["Date"] + "\n"
for part in mail.walk():
if part.is_multipart():
continue
if part.get_content_type() == 'text/plain':
body = "\n" + part.get_payload() + "\n"
dtypes = part.get_params(None, 'Content-Disposition')
if not dtypes:
if part.get_content_type() == 'text/plain':
continue
ctypes = part.get_params()
if not ctypes:
continue
for key,val in ctypes:
if key.lower() == 'name':
message += "Attachment:" + val + "\n"
break
else:
continue
else:
attachment,filename = None,None
for key,val in dtypes:
key = key.lower()
if key == 'filename':
filename = val
if key == 'attachment':
attachment = 1
if not attachment:
continue
message += "Attachment:" + filename + "\n"
if body:
message += body + "\n"
print message
print
これは、正しい方向に向かうのに十分なはずです。
于 2010-02-20T19:54:16.947 に答える
2
次のようにして、メールのプレーンテキストのみを取得できます。
connection.fetch(id, '(BODY[1])')
私が見た Gmail メッセージでは、セクション 1 にマルチパート ジャンクを含むプレーンテキストが含まれています。これはそれほど堅牢ではないかもしれません。
すべての添付ファイルなしで添付ファイルの名前を取得する方法がわかりません。私はパーシャルを使用しようとはしていません。
于 2010-08-11T00:59:34.420 に答える