In Python how to convert an `email.message.Message` object into an `email.message.EmailMessage` object

email, python, python-3.x, rfc822

Solution

Taking @ManuelJaco's comment I was able to create an `mbox` instance which contains automatically message objects of the type `email.message.EmailMessage`:

def make_EmailMessage(f):
    """Factory to create EmailMessage objects instead of Message objects"""
    return email.message_from_binary_file(f, policy=email.policy.default)

mbox = mailbox.mbox(mboxfile, factory=make_EmailMessage)

Note: When iterating over `mbox` all messages (even messages contained in a message!) are of the `email.message.EmailMessage` type.

Problem

From my understanding the `mbox` class in Python 3.6's standard library generates old-style message objects of the type `email.message.Message`. The newer class `email.message.EmailMessage` introduced in 3.4/3.6 offers easier access to the content of the message (via `get_content()` and `get_body()`). How can I convert the `email.message.Message` objects I get from the `mbox` iterator into `email.message.EmailMessage` objects?

Original source