简体   繁体   中英

How to get body message using IMAP

How can I get the body of the message using imaplib ?

The code below print None in the terminal

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'])

if using py2 use message_from_string not message_from_bytes , message_from_bytes is for 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')

if its a multpart email you need to loop over the parts...

for part in raw_email.get_payload():

and look at the content type

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

etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM