电子邮件正文文本?
大家好,我正在使用一个脚本,里面涉及到:
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有什么问题吗?(或者说我哪里做错了?)
1 个回答
4
来自email
文档:
你可以给解析器传一个字符串或者一个文件对象,解析器会返回这个对象结构的根消息实例。
对于简单的非MIME消息,这个根对象的内容通常是一个包含消息文本的字符串。而对于MIME消息,根对象会通过它的is_multipart()方法返回True,这样你就可以通过get_payload()和walk()方法来访问其中的子部分。
所以,如果你想获取内容,可以使用get_payload()
;如果消息是多部分的,那就先调用walk()
方法,然后在你想要的子部分上使用get_payload()
。