【问题标题】:python imap read email body return None after get_payloadpython imap读取电子邮件正文在get_payload后返回无
【发布时间】:2018-08-03 23:56:14
【问题描述】:

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

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

当我打印内容时,它会将我返回为无,但我的电子邮件有正文 任何人都可以帮助我吗?

【问题讨论】:

  • 你为什么要为 IMAP 使用名为 SMTP_SERVER 和 PORT 的变量?

标签: python imap imaplib


【解决方案1】:

来自the documentation

如果消息是多部分的并且 decode 标志是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)

【讨论】:

  • 谢谢回复,我试过使用 str(msg) 我读为 Content-Type: text/plain; charset="us-ascii",然后我取出解码,但它给了我:[, ]
  • 是的,多部分消息的.get_payload() 返回一个列表。在同一文档中,msg "is_multipart()True 时将是Message 对象的列表"。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 2013-04-30
    • 2023-03-18
    • 1970-01-01
    • 2017-05-13
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多