Search code examples
pythonemailmultipart

Python -Get the body of an multipart email


i get an email with the following code:

m = imaplib.IMAP4_SSL(MailReceiveSRV)
m.login(MailReceiveUSER, MailReceivePWD)
m.select("Inbox")
status, unreadcount = m.status('INBOX', "(UNSEEN)")
unreadcount = int(unreadcount[0].split()[2].strip(').,]'))
items = m.search(None, "UNSEEN")
items = str(items[1]).strip('[\']').split(' ')
for index, emailid in enumerate(items):
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)
    for part in mail.walk():
        body = part.get_payload()

FYI: This is always a part of the examplecode.

But body is now a biiig list of objects. If the Content_Type would be Plaintext, it would be much easier.

How can i get access to the body of that mail now?


Solution

  • Short answer

    You have a multiparted email. That's why you're getting a list instead of a string: get_payload returns a list of Message if it's a multipart message, and string if it's not.

    Explanation

    From the docs:

    Return the current payload, which will be a list of Message objects when is_multipart() is True, or a string when is_multipart() is False.

    Hence get_payload returning a list.

    Your code for getting the body would be something like:

    if email_message.is_multipart():
        for part in email_message.get_payload():
            body = part.get_payload()
            # more processing?
    else:
        body = email_message.get_payload()
    

    Again, from the docs:

    Note that is_multipart() returning True does not necessarily mean that "msg.get_content_maintype() == 'multipart'" will return the True. For example, is_multipart will return True when the Message is of type message/rfc822.