Python - 获取多部分电子邮件的正文

标签 python email multipart

我收到一封包含以下代码的电子邮件:

m = imaplib.IMAP4_SSL(MailReceiveSRV)
m.login(MailReceiveUSER, MailReceivePWD)
m.select("Inbox")
status, unreadcount = m.status('INBOX', "(UNSEEN)")
unreadcount = int(unreadcount[0].split()[2].strip(').,]'))
items = m.search(None, "UNSEEN")
items = str(items[1]).strip('[\']').split(' ')
for index, emailid in enumerate(items):
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)
    for part in mail.walk():
        body = part.get_payload()

仅供引用:这始终是示例代码的一部分。

但是 body 现在是一个很大的对象列表。如果 Content_Type 是纯文本,那就容易多了。

我现在如何才能访问该邮件的正文?

最佳答案

简短回答

您有一封由多部分组成的电子邮件。这就是为什么您得到的是列表而不是字符串:如果是多部分消息,则 get_payload 返回 Message 列表,如果是多部分消息,则返回 string不是。

说明

来自the docs :

Return the current payload, which will be a list of Message objects when is_multipart() is True, or a string when is_multipart() is False.

因此 get_payload 返回一个列表。

获取主体的代码类似于:

if email_message.is_multipart():
    for part in email_message.get_payload():
        body = part.get_payload()
        # more processing?
else:
    body = email_message.get_payload()

再次,from the docs :

Note that is_multipart() returning True does not necessarily mean that "msg.get_content_maintype() == 'multipart'" will return the True. For example, is_multipart will return True when the Message is of type message/rfc822.

关于Python - 获取多部分电子邮件的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30517621/

相关文章:

python - Matplotlib basemap 海岸坐标

python - 谷歌驱动器 API : The user has not granted the app error

php - 未从 mysql 数据库收到电子邮件

java - 改变 multipart/XXX 内容类型而不改变底层部分

java - 使用 JavaMail 在电子邮件中内嵌图像

python - 在 csv 文件中查找字符串时提取行

perl - 如何使用 MIME::Lite perl 检查上次发送的电子邮件是否已成功发送

javascript - 验证电子邮件或电话号码

scala - 播放 FakeMultipartRequest 意外输入结束

python - Gensim 的 Doc2vec - 推断的向量不相似