python - 电子邮件正文?

标签 python email

大家好,我正在使用一个脚本,其中涉及:

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/

相关文章:

python - 根据字符串长度追加

python - 如何改变python中的时间?

python sys.stdin.read() 来自 tail -f

java - 在 Java 中替换字符串中的电子邮件

email - 如何抑制已读回执?

laravel - 在 Laravel 中发送电子邮件通知之前检查用户设置

python - Tkinter 绘制矩形未按预期工作

Python在html元素末尾查找文本

java - 从 Java 应用程序发送电子邮件的最佳方式

java - 如何使用 java api 使用 Outlook 发送电子邮件