大家好,我正在使用一个脚本,其中涉及:
import oauth2 as oauth
import oauth2.clients.imap as imaplib
import email
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4
# This is the only thing in the API for impaplib.IMAP4_SSL that has
# changed. You now authenticate with the URL, consumer, and token.
conn.authenticate(url, consumer, token)
# Once authenticated everything from the impalib.IMAP4_SSL class will
# work as per usual without any modification to your code.
conn.select('[Gmail]/All Mail')
response, item_ids = conn.search(None, "SINCE", "01-Jan-2011")
item_ids = item_ids[0].split()
# Now iterate through this shit and retrieve all the email while parsing
# and storing into your whatever db.
for emailid in item_ids:
resp, data = conn.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
我当前的问题是我似乎无法检索 mail
实例的正文。我可以通过打印或 mail.as_string() 来查看电子邮件的内容,但即使使用 mail.keys() 和 mail.values() 我实际上也无法看到邮件的内容(主要消息)。
这个电子邮件库 API 有什么问题? (或者更确切地说我做错了什么)?
最佳答案
来自email
docs :
You can pass the parser a string or a file object, and the parser will return to you the root Message instance of the object structure.
For simple, non-MIME messages the payload of this root object will likely be a string containing the text of the message. For MIME messages, the root object will return True from its is_multipart() method, and the subparts can be accessed via the get_payload() and walk() methods.
因此,请使用 get_payload()
或者如果消息是多部分的,则调用 walk()
方法,然后在所需的位置上使用 get_payload()
子部分。
关于python - 电子邮件正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8005320/