On this page
  1. mailbox
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Locking and Flushing on Updates
  7. Gotchas & Boundaries
  8. Classes & Objects

mailbox

Prev: lzma | Up: stdlib_module | Next: marshal
Rel: email, json, mimetypes, base64, binascii
Ref: docs.python.org — mailbox
Tags: #public #python3 #stdlib


Import

import mailbox

Overview

Reader and writer for local on-disk email mailbox formats (mbox, Maildir, MH, Babyl, MMDF). Use mailbox to parse exported .mbox archives (like Google Takeout mail exports), inspect local Maildir spools, or convert between local mailbox formats alongside email.

Quick Start

import mailbox
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    mbox_path = Path(tmp) / "archive.mbox"
    box = mailbox.mbox(mbox_path)
    try:
        msg = mailbox.mboxMessage()
        msg["From"] = "alice@example.com"
        msg["Subject"] = "Release notes"
        msg.set_payload("v1.0 is live.")
        box.add(msg)
        box.flush()
    finally:
        box.close()

    with mailbox.mbox(mbox_path) as reader:
        subjects = [m["Subject"] for m in reader]
assert subjects == ["Release notes"]

Implementation Walkthrough

1. Safe Locking and Flushing on Updates

Single-file formats like mbox rewrite the entire file on flush(), so always lock before mutating and release in a finally block:

import mailbox

def delete_by_subject(mbox_path: str, target: str) -> int:
    removed = 0
    box = mailbox.mbox(mbox_path)
    box.lock()
    try:
        for key, msg in list(box.items()):
            if msg["Subject"] == target:
                box.remove(key)
                removed += 1
        box.flush()
    finally:
        box.unlock()
        box.close()
    return removed

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes