20

I am trying to print the content of the mail ( Mail body) using Python mailbox.

import mailbox

mbox = mailbox.mbox('Inbox')
i=1
for message in mbox:
    print i
    print "from   :",message['from']
    print "subject:",message['subject']
    print "message:",message['**messages**']
    print "**************************************" 
    i+=1

But I feel message['messages'] is not the right one to print the mail content here. I could not understand it from the documentation

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Technopolice
  • 467
  • 2
  • 5
  • 12
  • It is clearer to use: `for i, message in enumerate(mbox):`, you could remove then `i=1` and `i+=1` – Nir Dec 03 '20 at 12:28

2 Answers2

21

To get the message content, you want to use get_payload(). mailbox.Message is a subclass of email.message.Message. You'll also want to check is_multipart() because that will affect the return value of get_payload(). Example:

if message.is_multipart():
    content = ''.join(part.get_payload(decode=True) for part in message.get_payload())
else:
    content = message.get_payload(decode=True)
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
19
def getbody(message): #getting plain text 'email body'
    body = None
    if message.is_multipart():
        for part in message.walk():
            if part.is_multipart():
                for subpart in part.walk():
                    if subpart.get_content_type() == 'text/plain':
                        body = subpart.get_payload(decode=True)
            elif part.get_content_type() == 'text/plain':
                body = part.get_payload(decode=True)
    elif message.get_content_type() == 'text/plain':
        body = message.get_payload(decode=True)
    return body

this function can give you message body if the body is plain text.

matanster
  • 15,072
  • 19
  • 88
  • 167
jOSe
  • 687
  • 11
  • 22