'How to get the body text of email with imaplib?

I am in python3.4 .

import imaplib
import email
user="XXXX"
password="YYYY"
con=imaplib.IMAP4_SSL('imap.gmail.com')
con.login(user,password)
con.list()

con.select("INBOX")
result,data=con.fetch(b'1', '(RFC822)')
raw=email.message_from_bytes(data[0][1])

>>> raw["From"]
'xxxx'
>>> raw["To"]
'[email protected]'
>>> raw["Subject"]
'Re:get the min date from a list'

When i run 'print(raw)' there are many lines of the body of the email ,
i can't get it with raw[TEXT] OR raw['TEXT'] OR raw['BODY'] ,
how can i get the body of the email text?



Solution 1:[1]

Following up using Python 3.8 - parses all the parts that have an associated encoding and turns it into a single HTML page

import imaplib
import email
import webbrowser
import tempfile
import webbrowser


def email_to_html(parsed):
    all_parts = []
    for part in parsed.walk():
        if type(part.get_payload()) == list:
            for subpart in part.get_payload():
                all_parts += email_to_html(subpart)
        else:
            if encoding := part.get_content_charset():
                all_parts.append(part.get_payload(decode=True).decode(encoding))
    return ''.join(all_parts)


# Login
imap = imaplib.IMAP4_SSL("imap.gmail.com")  
result = imap.login("username", "password")

# Select the inbox, grab only the unseen emails
status, resp = imap.select('INBOX')
status, response = imap.search(None, '(UNSEEN)')
unread_msg_nums = response[0].split()

email_bodies = []
for idx in unread_msg_nums:
    _, msg = imap.fetch(str(int(idx)), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            raw_email = response[1]
            parsed = email.message_from_bytes(raw_email)
            email_bodies.append(email_to_html(parsed))



# If you want to view/check the emails in your browser
def display(html):
    with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:
        url = 'file://' + f.name
        f.write(html)
        webbrowser.open(url)


for body in email_bodies:
    display(body)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JellyBeans