python imap 在 get_payload 之后读取电子邮件正文 return None

python imap read email body return None after get_payload

你好,我正在尝试阅读我的电子邮件,代码是:

FROM_EMAIL  = "emailadd"
FROM_PWD    = "pasword"
SMTP_SERVER = "imapaddress"
SMTP_PORT   = 111

mail = imaplib.IMAP4_SSL(SMTP_SERVER)

mail.login(FROM_EMAIL,FROM_PWD)

mail.select('inbox')


type,data = mail.search(None, '(SUBJECT "IP")')
msgList = data[0].split()
last=msgList[len(msgList)-1]
type1,data1 = mail.fetch(last, '(RFC822)')
msg=email.message_from_string(data1[0][1])
content = msg.get_payload(decode=True)


mail.close()
mail.logout()

当我打印内容时,它会以 None 的形式返回给我,但我的电子邮件有正文 谁能帮帮我?

来自 the documentation

If the message is a multipart and the decode flag is True, then None is returned.

寓意:在获取多部分消息时不要设置 解码 标志。

如果您要解析多部分消息,您可能会熟悉 relevant RFC。同时,quick-and-dirty 可能会为您提供所需的数据:

msg=email.message_from_string(data1[0][1])

# If we have a (nested) multipart message, try to get
# past all of the potatoes and straight to the meat
# For production, you might want a more thought-out
# approach, but maybe just fetching the first item
# will be sufficient for your needs
while msg.is_multipart():
    msg = msg.get_payload(0)

content = msg.get_payload(decode=True)

基于 ,这里是稍微复杂一些的代码:

msg=email.message_from_string(data1[0][1])
if msg.is_multipart():
    for part in email_message.walk():
        ctype = part.get_content_maintype()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text' and 'attachment' not in cdispo:
            body = part.get_payload(decode=True)  # decode
            break
# not multipart - plain text
else:
    body = msg.get_payload(decode=True)

这段代码主要取自this answer.