The mailbox module defines a common API for accessing email messages stored in local disk formats, including:

There are base classes for Mailbox and Message , and each mailbox format includes a corresponding pair of subclasses to implement the details for that format.

The mbox format is the simplest to show in documentation, since it is entirely plain text. Each mailbox is stored as a single file, with all of the messages concatenated together. Each time a line starting with "From " (“From” followed by a single space) is encountered it is treated as the beginning of a new message. Any time those characters appear at the beginning of a line in the message body, they are escaped by prefixing the line with ">" .

Creating an mbox Mailbox¶ Instantiate the mbox class by passing the filename to the constructor. If the file does not exist, it is created when add() is used to append messages. mailbox_mbox_create.py ¶ import mailbox import email.utils from_addr = email . utils . formataddr (( 'Author' , 'author@example.com' )) to_addr = email . utils . formataddr (( 'Recipient' , 'recipient@example.com' )) payload = '''This is the body. From (will not be escaped). There are 3 lines. ''' mbox = mailbox . mbox ( 'example.mbox' ) mbox . lock () try : msg = mailbox . mboxMessage () msg . set_unixfrom ( 'author Sat Feb 7 01:05:34 2009' ) msg [ 'From' ] = from_addr msg [ 'To' ] = to_addr msg [ 'Subject' ] = 'Sample message 1' msg . set_payload ( payload ) mbox . add ( msg ) mbox . flush () msg = mailbox . mboxMessage () msg . set_unixfrom ( 'author' ) msg [ 'From' ] = from_addr msg [ 'To' ] = to_addr msg [ 'Subject' ] = 'Sample message 2' msg . set_payload ( 'This is the second body.

' ) mbox . add ( msg ) mbox . flush () finally : mbox . unlock () print ( open ( 'example.mbox' , 'r' ) . read ()) The result of this script is a new mailbox file with two email messages. $ python3 mailbox_mbox_create.py From MAILER-DAEMON Sun Mar 18 20:20:59 2018 From: Author <author@example.com> To: Recipient <recipient@example.com> Subject: Sample message 1 This is the body. >From (will not be escaped). There are 3 lines. From MAILER-DAEMON Sun Mar 18 20:20:59 2018 From: Author <author@example.com> To: Recipient <recipient@example.com> Subject: Sample message 2 This is the second body.

Reading an mbox Mailbox¶ To read an existing mailbox, open it and treat the mbox object like a dictionary. The keys are arbitrary values defined by the mailbox instance and are not necessary meaningful other than as internal identifiers for message objects. mailbox_mbox_read.py ¶ import mailbox mbox = mailbox . mbox ( 'example.mbox' ) for message in mbox : print ( message [ 'subject' ]) The open mailbox supports the iterator protocol, but unlike true dictionary objects the default iterator for a mailbox works on the values instead of the keys. $ python3 mailbox_mbox_read.py Sample message 1 Sample message 2