【问题标题】:Python pull back plain text body from message from IMAP accountPython 从 IMAP 帐户的消息中拉回纯文本正文
【发布时间】:2011-09-22 18:59:01
【问题描述】:

我一直在努力解决这个问题。

我可以通过 imaplib 连接并获取邮件。

msrv = imaplib.IMAP4(server)
msrv.login(username,password)

# Get mail

msrv.select()

#msrv.search(None, 'ALL')

typ, data = msrv.search(None, 'ALL')

# iterate through messages
for num in data[0].split():
    typ, msg_itm = msrv.fetch(num, '(RFC822)')
    print msg_itm
    print num 

但我需要做的是将邮件正文作为纯文本获取,我认为这适用于电子邮件解析器,但我无法使其正常工作。

谁有一个完整的例子我可以看看?

谢谢,

【问题讨论】:

    标签: python parsing email imap plaintext


    【解决方案1】:

    为了获得电子邮件正文的纯文本版本,我做了这样的事情......

    xxx= data[0][1] #puts message from list into string
    
    
    xyz=email.message_from_string(xxx)# converts string to instance of message xyz is an email message so multipart and walk work on it.
    
    #Finds the plain text version of the body of the message.
    
    if xyz.get_content_maintype() == 'multipart': #If message is multi part we only want the text version of the body, this walks the message and gets the body.
        for part in xyz.walk():       
            if part.get_content_type() == "text/plain":
                body = part.get_payload(decode=True)
            else:
                        continue
    

    【讨论】:

    • 如果不是multipart?
    【解决方案2】:

    这是来自docs 的一个最小示例:

    import getpass, imaplib
    
    M = imaplib.IMAP4()
    M.login(getpass.getuser(), getpass.getpass())
    M.select()
    typ, data = M.search(None, 'ALL')
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
        print 'Message %s\n%s\n' % (num, data[0][1])
    M.close()
    M.logout()
    

    在这种情况下,data[0][1] 包含消息正文。

    【讨论】:

    • 谢谢。它给了我信息。有什么办法只得到身体而不是附件?
    • 试试这个:import email, msg = email.message_from_string(data[0][1])
    猜你喜欢
    • 1970-01-01
    • 2015-09-16
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多