1

我一直在努力,但我错过了这个标记。

我能够通过 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 

但我需要做的是将邮件正文作为纯文本获取,我认为这适用于电子邮件解析器,但我在让它工作时遇到问题。

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

谢谢,

4

2 回答 2

9

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

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
于 2011-09-23T17:31:54.007 回答
1

这是文档中的一个最小示例:

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] 包含消息正文。

于 2011-09-22T19:14:53.227 回答