mailbox
The Python mailbox module provides classes for reading, creating, and modifying on-disk mailboxes in several historical formats, including Maildir, mbox, MH, Babyl, and MMDF. Each format is exposed through a subclass of the abstract Mailbox class, which offers a dictionary-like mapping from keys to messages.
Here’s a quick example that appends a message to an mbox file and reads it back:
>>> import mailbox
>>> mbox = mailbox.mbox("demo.mbox")
>>> msg = mailbox.mboxMessage()
>>> msg["From"] = "alice@example.com"
>>> msg["Subject"] = "Hello"
>>> msg.set_payload("Hi there!")
>>> mbox.add(msg)
0
>>> mbox.flush()
>>> mbox.close()
>>> mailbox.mbox("demo.mbox")[0]["Subject"]
'Hello'
Key Features
- Reads and writes mailboxes in Maildir, mbox, MH, Babyl, and MMDF formats
- Exposes a dictionary-like interface for accessing messages by key
- Provides format-specific
Messagesubclasses that preserve flags, folders, and labels - Supports file locking with
.lock()and.unlock()for safe concurrent access - Iterates over messages without loading the entire mailbox into memory
- Builds on the
email.messagemodule to parse and serialize individual messages
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
mailbox.Mailbox |
Class | Defines the abstract base interface for all mailbox formats |
mailbox.Maildir |
Class | Represents a mailbox in Maildir format with one file per message |
mailbox.mbox |
Class | Represents a mailbox stored as a single file in mbox format |
mailbox.MH |
Class | Represents a mailbox in MH format with one file per message |
mailbox.Babyl |
Class | Represents a mailbox in Babyl format used by older Emacs clients |
mailbox.MMDF |
Class | Represents a mailbox in MMDF format similar to mbox |
mailbox.Message |
Class | Extends email.message.Message with mailbox-specific state |
mailbox.mboxMessage |
Class | Represents a message with mbox-specific headers and flags |
mailbox.MaildirMessage |
Class | Represents a message with Maildir subdirectory and flag info |
mailbox.NoSuchMailboxError |
Exception | Signals that a requested mailbox does not exist on disk |
mailbox.ExternalClashError |
Exception | Signals a conflict with another process modifying the mailbox |
Examples
Create a Maildir mailbox and add a message to it:
>>> import mailbox
>>> md = mailbox.Maildir("Mail")
>>> msg = mailbox.MaildirMessage()
>>> msg["Subject"] = "Weekly report"
>>> msg["From"] = "team@example.com"
>>> msg.set_payload("All systems nominal.")
>>> key = md.add(msg)
>>> len(md)
1
Iterate over all messages in an existing mbox file and print their subjects:
>>> import mailbox
>>> for message in mailbox.mbox("archive.mbox"):
... print(message["Subject"])
...
Welcome
Invoice 42
Re: Welcome
Safely modify a mailbox by acquiring a lock first:
>>> import mailbox
>>> mbox = mailbox.mbox("archive.mbox")
>>> mbox.lock()
>>> try:
... del mbox[0]
... mbox.flush()
... finally:
... mbox.unlock()
... mbox.close()
...
Common Use Cases
The most common tasks for mailbox include:
- Archiving messages from a local mail client into a portable format
- Migrating messages between Maildir, mbox, and other formats
- Building scripts that process saved email offline, such as search and statistics
- Backing up a mailbox before running a risky operation against a live mail server
- Extracting attachments or headers from stored messages for data analysis
Real-World Example
Consider a situation where you have an archive.mbox file exported from a mail client and you want to list every message along with its sender and subject:
list_messages.py
import mailbox
archive = mailbox.mbox("archive.mbox")
try:
for key, message in archive.iteritems():
sender = message["From"] or "unknown"
subject = message["Subject"] or "(no subject)"
print(f"{key}: {sender} -> {subject}")
finally:
archive.close()
Running the script prints one line per stored message:
$ python list_messages.py
0: user0@example.com -> Welcome
1: user1@example.com -> Invoice 42
2: user2@example.com -> Re: Welcome
The mailbox.mbox class exposes the archive as a dictionary-like object, so you can walk over keys and messages without parsing the raw file yourself.
Related Resources
Tutorial
Sending Emails With Python
In this tutorial, you'll learn how to send emails using Python. Find out how to send plain-text and HTML messages, add files as attachments, and send personalized emails to multiple people.
For additional information on related topics, take a look at the following resources:
- Reading and Writing Files in Python (Guide) (Tutorial)
- Dictionaries in Python (Tutorial)
- Iterators and Iterables in Python: Run Efficient Iterations (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Working With Files in Python (Tutorial)
- Python's pathlib Module: Taming the File System (Tutorial)
- Sending Emails Using Python (Course)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Using Dictionaries in Python (Course)
- Dictionaries in Python (Quiz)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)
- Practical Recipes for Working With Files in Python (Course)
- Working With Files in Python (Quiz)
- Using Python's pathlib Module (Course)
- Python's pathlib Module: Taming the File System (Quiz)
By Leodanis Pozo Ramos • Updated April 23, 2026