Skip to content

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:

Language: Python
>>> 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 Message subclasses 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.message module 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:

Language: Python
>>> 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:

Language: Python
>>> 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:

Language: Python
>>> 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:

Language: Python Filename: 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:

Language: Shell
$ 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.

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.

intermediate web-dev

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 23, 2026