从IMAP账户中提取邮件的纯文本正文
我一直在研究这个问题,但总是没能做到。
我可以通过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
但是我需要做的是把邮件的内容提取为纯文本,我觉得可以用邮件解析器来实现,但我在使用时遇到了问题。
有没有人能给我一个完整的例子让我参考一下?
谢谢!
2 个回答
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]里包含了消息的内容。
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