pythonemailmbox

Show the full original source of an email with Python


The main answer of Reading the mail content of an mbox file using python mailbox shows how to display the content of an email from a .mbox file:

if message.is_multipart():
    content = ''.join(part.get_payload(decode=True) for part in message.get_payload())
else:
    content = message.get_payload(decode=True)

However this does not show the "full original source" of the email ; I mean what we can have in nearly all webmails when clicking "Show original message":

Delivered-To: ...
Return-Path: ...
...

How to get this with Python mailbox?

enter image description here


Solution

  • If message is a Python email.message.EmailMessage object (or the legacy email.massage.Message class from before Python 3.5), simply call its .as_string() method.

    The payload method quite specifically extracts only one MIME part.