在多部分电子邮件中,email.message.Message.get_payload()返回一个列表,其中包含每个部分的一个项目。最简单的方法是步行消息并获取每个部分的有效载荷:

import email
msg = email.message_from_string(raw_message)
for part in msg.walk():
# each part is a either non-multipart, or another multipart message
# that contains further parts... Message is organized like a tree
if part.get_content_type() == 'text/plain':
print part.get_payload() # prints the raw text

对于非多部分消息,无需执行所有步骤。你可以直接去get_payload(),不管content_type如何。

msg = email.message_from_string(raw_message)
msg.get_payload()

如果内容被编码,则需要将None作为第一个参数传递给get_payload(),后跟True(解码标志是第二个参数)。例如,假设我的电子邮件包含MS Word文档附件:

msg = email.message_from_string(raw_message)
for part in msg.walk():
if part.get_content_type() == 'application/msword':
name = part.get_param('name') or 'MyDoc.doc'
f = open(name, 'wb')
f.write(part.get_payload(None, True)) # You need None as the first param
# because part.is_multipart()
# is False
f.close()

为了获得HTML部分的合理的纯文本近似值,我发现html2text的工作效果很好。