如何使用IMAP获取正文消息

时间:2019-05-24 22:37:53

标签: python

如何使用 imaplib 获取邮件正文?

下面的代码在终端中不显示任何内容

mail.login("email@hotmail.com", "pass")
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.

result, data = mail.search(None, '(FROM "sender@hotmail.com")')

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
msg = email.message_from_bytes(raw_email)

print(msg['Body'])

1 个答案:

答案 0 :(得分:0)

如果使用py2,请使用message_from_string而不是message_from_bytesmessage_from_bytes用于py3

import email
raw_email = email.message_from_string(data[0][1])
if not raw_email.is_multipart():
    print unicode(raw_email.get_payload(decode=True), raw_email.get_content_charset(), 'ignore').encode('utf8', 'replace')

如果是多件电子邮件,则需要遍历各个部分...

for part in raw_email.get_payload():

并查看内容类型

if part.get_content_type() == 'text/plain':
    print unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace')

等等。