Reading the mail content of an mbox file using python mailbox

Technopolice picture Technopolice · Oct 26, 2014 · Viewed 19.4k times · Source

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

Answer

All Workers Are Essential picture All Workers Are Essential · Oct 26, 2014

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)