halloleo
halloleo

Reputation: 10384

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

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?

Upvotes: 12

Views: 4290

Answers (2)

halloleo
halloleo

Reputation: 10384

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.

Upvotes: 7

Ayushman Verma
Ayushman Verma

Reputation: 47

To create an email.message.EmailMessage object, change the policy in parser to email.policy.default.

msg = email.message_from_string(raw_email_string,
                            policy = email.policy.default)

Upvotes: 4

Related Questions