python imap读取电子邮件正文返回get_payload之后没有

时间:2018-02-23 20:57:29

标签: python imap imaplib

您好,我试图阅读我的电子邮件,代码是:

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()

当我打印内容时,它会返回为“无”,但我的电子邮件中包含正文 有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

来自the documentation

  

如果邮件是多部分且解码标志为True,则会返回None

道德:在获取多部分消息时,请勿设置 decode 标志。

如果要解析多部分消息,可能会熟悉relevant RFC。同时,这种快速和肮脏可能会为您提供所需的数据:

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)

答案 1 :(得分:0)

Rob's answer为基础,下面是稍微复杂的代码:

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