mail_deduplicate.mail_box module

Utilities to read and write mail boxes in various formats.

Based on Python’s standard library mailbox module.

exception mail_deduplicate.mail_box.MailSourceError(message)[source]

Bases: ClickException

A mail source that cannot be used as given.

Raised for a problem the user can fix: a folder with no structure mdedup recognizes, a box another program locked, a source given twice. Click prints it as a one-line Error:, with no traceback and no invitation to report a bug.

mail_deduplicate.mail_box.maildir_subpath(box, key)[source]

Path of a maildir mail below its box, read from the table of contents.

A maildir key drops the :2,<flags> suffix the file name carries, so the name cannot be rebuilt from the key alone. The box refreshed its table of contents to hand out the mail in the first place, so it is only re-validated on a miss.

Return type:

str

mail_deduplicate.mail_box.maildir_mail_path(box, key)[source]

Location of a maildir mail, read from the box’s table of contents.

Return type:

str

mail_deduplicate.mail_box.keyed_mail_path(box, key)[source]

Location of an MH mail, whose file is named after its key.

Return type:

str

mail_deduplicate.mail_box.eml_mail_path(box, key)[source]

Location of an eml mail: a file below its box, or the file its box is.

An eml box opened on a single mail file holds that file alone.

Return type:

str

mail_deduplicate.mail_box.box_file_path(box, key)[source]

Location of a mail from a file-based box: the box’s own single file.

Every mail of an mbox, babyl or mmdf box is packed into it, so they all share this path and are told apart by their mail ID.

Return type:

str

mail_deduplicate.mail_box.iter_mail_ids(box)[source]

Yields the key of every mail held by a box.

Maildir.iterkeys() confirms that each key still resolves to a file, one stat per mail, on top of the directory listing it has just built. Every caller here goes on to stat or open that same file anyway, and copes with its disappearance, so the check is paid for twice and needed once: reading the refreshed table of contents directly skips it.

The other formats list their mails without that extra round, and are left to their own iterator.

Return type:

Iterator[str]

mail_deduplicate.mail_box.resolve_mail_path(box, key)[source]

Location of a mail in its box, without instantiating the mail.

Lets a caller reach a mail’s file before deciding to read it, which is how the hash cache checks whether a mail changed without paying for its parsing.

Return type:

str

mail_deduplicate.mail_box.make_dedup_mail(name, base, path_resolver)[source]

Create a DedupMail class for a mailbox message type.

Deriving a mail’s own location from its box is format-specific, so the resolver is baked into the class here instead of being branched on at runtime.

Return type:

type

class mail_deduplicate.mail_box.MaildirDedupMail(message=None)

Bases: DedupMailMixin, MaildirMessage

Initialize a MaildirMessage instance.

static resolve_path(box, key)

Location of a maildir mail, read from the box’s table of contents.

Return type:

str

class mail_deduplicate.mail_box.mboxDedupMail(message=None)

Bases: DedupMailMixin, mboxMessage

Initialize an mboxMMDFMessage instance.

static resolve_path(box, key)

Location of a mail from a file-based box: the box’s own single file.

Every mail of an mbox, babyl or mmdf box is packed into it, so they all share this path and are told apart by their mail ID.

Return type:

str

class mail_deduplicate.mail_box.MHDedupMail(message=None)

Bases: DedupMailMixin, MHMessage

Initialize an MHMessage instance.

static resolve_path(box, key)

Location of an MH mail, whose file is named after its key.

Return type:

str

class mail_deduplicate.mail_box.BabylDedupMail(message=None)

Bases: DedupMailMixin, BabylMessage

Initialize a BabylMessage instance.

static resolve_path(box, key)

Location of a mail from a file-based box: the box’s own single file.

Every mail of an mbox, babyl or mmdf box is packed into it, so they all share this path and are told apart by their mail ID.

Return type:

str

class mail_deduplicate.mail_box.MMDFDedupMail(message=None)

Bases: DedupMailMixin, MMDFMessage

Initialize an mboxMMDFMessage instance.

static resolve_path(box, key)

Location of a mail from a file-based box: the box’s own single file.

Every mail of an mbox, babyl or mmdf box is packed into it, so they all share this path and are told apart by their mail ID.

Return type:

str

class mail_deduplicate.mail_box.EMLDedupMail(message=None)

Bases: DedupMailMixin, Message

Initialize a Message instance.

static resolve_path(box, key)

Location of an eml mail: a file below its box, or the file its box is.

An eml box opened on a single mail file holds that file alone.

Return type:

str

class mail_deduplicate.mail_box.EML(dirname, factory=None, create=True)[source]

Bases: Mailbox

A folder of loose .eml files, walked recursively, or one mail file alone.

Supports mail archives exported as individual RFC 5322 files, one mail per file, as produced by Outlook PST/OST conversion tools for instance. See: https://github.com/kdeldycke/mail-deduplicate/issues/760

Keys are the paths of the mail files, relative to the folder’s root. Files without the .eml extension (case-insensitive) are ignored, as well as hidden files and directories.

A box opened on a file holds that one mail, whatever the name of the file. Its key is the name of the file, and the box takes no other mail.

Follows the interface of Python’s mailbox.Mailbox. Like maildir, the one-file-per-mail storage needs no locking.

Initialize a Mailbox instance.

iterkeys()[source]

Return an iterator over keys.

get_file(key)[source]

Return a file-like representation or raise a KeyError.

get_bytes(key)[source]

Return a byte string representation or raise a KeyError.

Return type:

bytes

get_message(key)[source]

Return a Message representation or raise a KeyError.

add(message)[source]

Add message and return assigned key.

Return type:

str

remove(key)[source]

Remove the keyed message; raise KeyError if it doesn’t exist.

Return type:

None

list_folders()[source]

No subfolder objects: the recursive walk covers nested directories.

Return type:

list[str]

get_folder(folder)[source]
flush()[source]

Mails are written straight to the filesystem: nothing to flush.

Return type:

None

lock()[source]

One-file-per-mail storage needs no locking.

Return type:

None

unlock()[source]

One-file-per-mail storage needs no locking.

Return type:

None

close()[source]

No resource is kept open between operations.

Return type:

None

class mail_deduplicate.mail_box.BoxStructure(*values)[source]

Bases: Enum

Box structures can be file-based or folder-based.

FOLDER = 1
FILE = 2
class mail_deduplicate.mail_box.BoxFormat(*values)[source]

Bases: Enum

IDs of all the supported box formats and their metadata.

Each entry is associated to:

  • their original base class,

  • the structure they implement (file-based or folder-based),

  • the custom message factory class to use.

From these, we can derive the proper constructor with our own custom DedupMail factory.

Todo

Add support for other mailbox formats and sources, like Gmail accounts, IMAP servers, etc.

MAILDIR = (<class 'mailbox.Maildir'>, BoxStructure.FOLDER, <class 'mail_deduplicate.mail_box.MaildirDedupMail'>)
MBOX = (<class 'mailbox.mbox'>, BoxStructure.FILE, <class 'mail_deduplicate.mail_box.mboxDedupMail'>)
MH = (<class 'mailbox.MH'>, BoxStructure.FOLDER, <class 'mail_deduplicate.mail_box.MHDedupMail'>)
BABYL = (<class 'mailbox.Babyl'>, BoxStructure.FILE, <class 'mail_deduplicate.mail_box.BabylDedupMail'>)
MMDF = (<class 'mailbox.MMDF'>, BoxStructure.FILE, <class 'mail_deduplicate.mail_box.MMDFDedupMail'>)
EML = (<class 'mail_deduplicate.mail_box.EML'>, BoxStructure.FOLDER, <class 'mail_deduplicate.mail_box.EMLDedupMail'>)
property constructor

Return a constructor for this box format with our custom message factory.

mail_deduplicate.mail_box.FOLDER_FORMATS = (BoxFormat.MAILDIR, BoxFormat.MH, BoxFormat.EML)

Box formats implementing a folder-based structure.

Is a tuple to keep natural order defined by BoxFormat.

mail_deduplicate.mail_box.FILE_FORMATS = (BoxFormat.MBOX, BoxFormat.BABYL, BoxFormat.MMDF)

Box formats implementing a file-based structure.

Is a tuple to keep natural order defined by BoxFormat.

mail_deduplicate.mail_box.FOLDER_FORMAT_CLASSES = (<class 'mailbox.Maildir'>, <class 'mailbox.MH'>, <class 'mail_deduplicate.mail_box.EML'>)

Base classes of folder-based box formats, as a tuple ready for isinstance.

mail_deduplicate.mail_box.MAILDIR_SUBDIRS = frozenset({'cur', 'new', 'tmp'})

Sub-folders of a maildir, which hold its mails and are never folders of their own.

mail_deduplicate.mail_box.MAILDIR_REQUIRED_SUBDIRS = frozenset({'cur', 'tmp'})

Sub-folders a directory needs to be read as a maildir.

new may be missing: Thunderbird creates the maildir of a folder with cur and tmp only, as new holds the mails that no client saw yet. See nsMsgMaildirStore::CreateMaildir() in Thunderbird’s source code.

mail_deduplicate.mail_box.MH_SEQUENCES = '.mh_sequences'

File that holds the sequences of an MH folder, like unseen.

Autodetection reads a folder as MH only when it holds this file. Numbered mail files are not enough: without this file, MH.lock() fails before Python 3.13, and creates it in the folder from Python 3.13 on.

mail_deduplicate.mail_box.MBOX_FAMILY = (<class 'mailbox.mbox'>, <class 'mailbox.MMDF'>)

Formats keeping an envelope From line before each mail.

The standard library reads and writes both with the same code, so the line travels from one to the other.

mail_deduplicate.mail_box.PROFILE_LOCK = '.parentlock'

File that Thunderbird locks in its profile directory while it runs.

See nsProfileLock::Lock() in Firefox’s source code, which Thunderbird shares.

mail_deduplicate.mail_box.MAIL_START = re.compile(b'[!-9;-~]+:')

The start of a file holding one mail saved alone: the name of its first header.

A header name is printable ASCII but the colon. An mbox file starts with the From line of its first mail instead, an mmdf file with MMDF_START and a babyl file with BABYL_START, none of which matches.

mail_deduplicate.mail_box.BABYL_START = b'BABYL OPTIONS:'

The start of a babyl file: the first line of its options header.

Emacs Rmail writes BABYL OPTIONS: -*- rmail -*-, and the standard library BABYL OPTIONS: alone.

mail_deduplicate.mail_box.MMDF_START = b'\x01\x01\x01\x01'

The start of an mmdf file: the four Control-A characters that open each mail.

mail_deduplicate.mail_box.is_mh(path)[source]

Returns True when the path holds the MH_SEQUENCES file of MH.

Return type:

bool

mail_deduplicate.mail_box.is_maildir(path)[source]

Returns True when the path holds the sub-directories of a maildir.

Return type:

bool

mail_deduplicate.mail_box.holds_cur(path)[source]

Returns True when the path holds the cur sub-directory of a maildir.

A maildir copied by a tool that skips empty folders, like git, keeps its cur but can lose its tmp, which is_maildir() requires.

Return type:

bool

mail_deduplicate.mail_box.lacks_new(box)[source]

Returns True for a maildir box with no new, like a Thunderbird folder.

Return type:

bool

mail_deduplicate.mail_box.contains_maildir(path, test=<function is_maildir>)[source]

Returns True when the path is a maildir or holds one at any depth.

Allows the discovery of nested maildir folders stored as plain directories, as produced by isync/mbsync’s Verbatim naming style. See: https://github.com/kdeldycke/mail-deduplicate/issues/973

Dot-prefixed directories are ignored, as they are covered by the Maildir++ folder convention. The mail-holding sub-directories of maildirs are not explored either.

test tells a maildir apart, with is_maildir() by default.

Return type:

bool

mail_deduplicate.mail_box.contains_eml(path)[source]

Returns True when the path holds at least one .eml file, at any depth.

Hidden files and directories are ignored, and the extension is matched case-insensitively, mirroring the walk of EML boxes.

Return type:

bool

mail_deduplicate.mail_box.hidden_by_thunderbird(name)[source]

Returns True for a file or directory name Thunderbird never shows as a folder.

A name starting with . or # or ending with ~ is a hidden, autosave or backup file: Thunderbird stores a folder with such a name under a hashed file name. The other names are the .msf summaries of the folders, and the .mozmsgs directories where Thunderbird writes files for the search of the operating system. See nsShouldIgnoreFile() in Thunderbird’s source code.

Return type:

bool

mail_deduplicate.mail_box.is_mbox_file(path)[source]

Returns True when the file holds an mbox box.

An mbox file starts with the From line of its first mail. An empty folder of Thunderbird is an empty file, recognized by the .msf summary beside it. Thunderbird writes the summary when it creates a folder, and writes it again when it opens a folder that lost it.

Return type:

bool

mail_deduplicate.mail_box.iter_mbox_files(path)[source]

Yields every mbox file of a directory tree, in a stable order.

The walk enters every directory, so the tree can be one Thunderbird account, like Mail/Local Folders, or the whole Mail directory. Thunderbird keeps the sub-folders of a folder in its <folder>.sbd directory. The walk skips the names Thunderbird never shows as folders, with all they hold.

Return type:

Iterator[Path]

mail_deduplicate.mail_box.contains_mbox(path)[source]

Returns True when the path holds at least one mbox file, at any depth.

Return type:

bool

mail_deduplicate.mail_box.file_box_format(path)[source]

Returns the format of the box a file holds, from the bytes it starts with.

A file that starts with BABYL_START is a babyl box, and one that starts with MMDF_START an mmdf box. A file that starts with MAIL_START holds one mail saved alone, as an .eml does: RFC 5322 puts that start within the first 1,000 bytes of the file, as no line of a mail is longer. Any other file is an mbox, an unreadable one too: opening it then reports the error.

Return type:

BoxFormat

mail_deduplicate.mail_box.profile_lock_held(lock)[source]

Returns True when another process holds the lock file of a profile.

On Linux and macOS, Thunderbird holds an fcntl lock on the file, which ends with its process. The lock is tried here without waiting, and released at once. On Windows, Thunderbird keeps the file open with no sharing, so opening it fails.

The file stays in the profile after Thunderbird quits: only the lock tells. A lock that cannot be tried, like on a network file system, counts as free.

Return type:

bool

mail_deduplicate.mail_box.thunderbird_profile_in_use(path)[source]

Returns the Thunderbird profile holding path, if Thunderbird has it open.

The profile is the nearest directory above path that holds a PROFILE_LOCK file. A path outside any profile, like an account whose directory was moved out of it, returns None.

Return type:

Path | None

mail_deduplicate.mail_box.autodetect_box_type(path)[source]

Auto-detect the format of the mailbox located at the provided path.

A file is a babyl box, an mmdf box or an eml box of one mail saved alone when it starts like one, and an mbox otherwise: see file_box_format().

A folder takes the first format that fits:

  1. MH, when it holds the MH_SEQUENCES file.

  2. maildir, when it holds the MAILDIR_REQUIRED_SUBDIRS sub-directories, or nested maildir folders at any depth, like the folders of a Thunderbird account of one file per message.

  3. eml, when it holds loose .eml files.

  4. A tree of mbox boxes, when it holds mbox files at any depth, like the folders of a Thunderbird account.

Return type:

BoxFormat

mail_deduplicate.mail_box.open_box(path, box_format=None, force_unlock=False)[source]

Open a mail box.

Returns a list of boxes, one per sub-folder. All are locked, ready for operations.

If box_format is provided, forces the opening of the box in the specified format. Else, defaults to autodetection.

A directory opened as mbox gives one box per mbox file of its tree.

Return type:

list[Mailbox]

mail_deduplicate.mail_box.lock_box(box, force_unlock)[source]

Lock an opened box and allows for forced unlocking.

Returns the locked box. Raises MailSourceError if another lock holds the box and force_unlock is not set.

Return type:

Mailbox

mail_deduplicate.mail_box.release_box(box)[source]

Unlock a box and close its file, without writing its pending changes.

Mailbox.close() first writes the pending changes of a single-file box, which rewrites the whole file when a mail was removed. A run cut short by an error or an interrupt calls this instead: its single-file boxes stay as the run found them, and an interrupt does not start a rewrite.

Unlike MH.close(), this also closes the .mh_sequences file that a refused MH.lock() leaves open.

Return type:

None

mail_deduplicate.mail_box.open_subfolders(box, force_unlock)[source]

Browse recursively the subfolder tree of a box.

Returns a list of opened and locked boxes, each for one subfolder. If a subfolder cannot be locked, because another program holds it for instance, the boxes locked before it are unlocked again and the error is raised: the next run then needs no --force-unlock for them.

Skips box types not supporting subfolders. For maildir, both the Maildir++ convention (dot-prefixed folders) and Verbatim-style layouts (nested plain directories, each a maildir of its own) are browsed. A directory without the maildir structure only acts as a container of nested folders and carries no mail of its own.

Maildir lists the mails of new and cur each time it refreshes its table of contents, and fails on a missing one. A maildir with no new, like a Thunderbird folder, gets cur alone to list. Maildir.add() would still file a mail in the missing new, but mails are only added to the boxes a run creates.

A directory that holds a cur but no tmp is a maildir that lost its empty tmp, like in a git copy. Its mails are not read, and a warning names it, at any depth of the tree.

Return type:

list[Mailbox]

mail_deduplicate.mail_box.open_mbox_tree(path, force_unlock)[source]

Open each mbox file of a directory tree as a box of its own.

Returns the list of opened and locked boxes. Like open_subfolders(), if a box cannot be locked, the boxes locked before it are unlocked again and the error is raised. A .lock file left behind in a Thunderbird account would show up there as a folder.

Return type:

list[Mailbox]

mail_deduplicate.mail_box.carry_maildir_metadata(source, key, target, new_key)[source]

Give a copied maildir mail the folder, flags and time of its original.

A maildir keeps the state of a mail outside of its content: the new or cur folder says whether a client saw it, the :2, suffix of its file name holds its flags, and the modification time of the file is its delivery time, which IMAP servers like Dovecot serve as the internal date of the mail. Maildir.add() takes them from a MaildirMessage alone, so a mail added as bytes lands in new with no flags and the time of the run: it is renamed and re-dated afterwards.

Return type:

None

mail_deduplicate.mail_box.carry_mh_sequences(source, key, target, new_key)[source]

Enroll a copied MH mail in the sequences of its original.

MH keeps the state of a mail (unseen, replied, flagged) in the .mh_sequences file of its folder, by the number of the mail. MH.add() takes them from an MHMessage alone, so they are written here for a mail added as bytes, the way MH.add() writes them.

Return type:

None

mail_deduplicate.mail_box.add_mail(box, mail)[source]

Add a mail to a box, as the bytes its source box holds.

Every box format writes a mail handed over as a message with BytesGenerator, from the message parsed out of it. The generator does not write the mail back: it rebuilds it. It redraws each multipart boundary, closes one left open, turns a bare \r into a line break, and cannot write at all a multipart part parsed with no subpart, which python/cpython#136686 tracks. Deduplicating a mail is no reason to repair it, so every mail goes in as bytes, which each format writes as they are. See: https://github.com/kdeldycke/mail-deduplicate/issues/1090

Line endings are the one conversion left. They are reduced to LF before the write, as every box format but eml writes \n as the line separator of the platform, and would double the CR of a CRLF ending on Windows. An mbox or MMDF box also quotes the body lines starting with From, as its format requires.

The bytes do not include what a format keeps beside each mail: the envelope From line of an mbox or MMDF mail, the folder, flags and modification time of a maildir mail, the sequences of an MH mail, the labels of a Babyl mail. The first three travel with the mail into a box of the same format, and the envelope line also travels between mbox and MMDF, which keep it alike. A box of another format has no place for them, and nothing is translated: a maildir mail copied into an mbox gets no Status header. Babyl labels are not carried, as the standard library takes them from a BabylMessage alone.

Return type:

None

mail_deduplicate.mail_box.create_box(path, box_format, export_append=False)[source]

Creates a brand new box from scratch.

Return type:

Mailbox