Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
halloleo Avatar asked Aug 12 '19 05:08

halloleo


People also ask

What is EmailMessage () in Python?

It is the base class for the email object model. EmailMessage provides the core functionality for setting and querying header fields, for accessing message bodies, and for creating or modifying structured messages. An email message consists of headers and a payload (which is also referred to as the content).

What is email module in Python?

The email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib and nntplib .

What is Set_payload in Python?

In Python, set_payload is a method of the class email.message.Message() 22nd February 2019, 12:36 PM. Ulisses Cruz.


1 Answers

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=epolicy.default)

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

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

like image 170
halloleo Avatar answered Sep 28 '22 07:09

halloleo