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:
ClickExceptionA 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
maildirmail 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:
- mail_deduplicate.mail_box.maildir_mail_path(box, key)[source]¶
Location of a
maildirmail, read from the box’s table of contents.- Return type:
- mail_deduplicate.mail_box.keyed_mail_path(box, key)[source]¶
Location of an
MHmail, whose file is named after its key.- Return type:
- mail_deduplicate.mail_box.eml_mail_path(box, key)[source]¶
Location of an
emlmail: a file below its box, or the file its box is.An
emlbox opened on a single mail file holds that file alone.- Return type:
- 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,babylormmdfbox is packed into it, so they all share this path and are told apart by their mail ID.- Return type:
- 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, onestatper 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.
- 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:
- 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:
- class mail_deduplicate.mail_box.MaildirDedupMail(message=None)¶
Bases:
DedupMailMixin,MaildirMessageInitialize a MaildirMessage instance.
- class mail_deduplicate.mail_box.mboxDedupMail(message=None)¶
Bases:
DedupMailMixin,mboxMessageInitialize an mboxMMDFMessage instance.
- class mail_deduplicate.mail_box.MHDedupMail(message=None)¶
Bases:
DedupMailMixin,MHMessageInitialize an MHMessage instance.
- class mail_deduplicate.mail_box.BabylDedupMail(message=None)¶
Bases:
DedupMailMixin,BabylMessageInitialize a BabylMessage instance.
- class mail_deduplicate.mail_box.MMDFDedupMail(message=None)¶
Bases:
DedupMailMixin,MMDFMessageInitialize an mboxMMDFMessage instance.
- class mail_deduplicate.mail_box.EMLDedupMail(message=None)¶
Bases:
DedupMailMixin,MessageInitialize a Message instance.
- class mail_deduplicate.mail_box.EML(dirname, factory=None, create=True)[source]¶
Bases:
MailboxA folder of loose
.emlfiles, 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
.emlextension (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.
- class mail_deduplicate.mail_box.BoxStructure(*values)[source]¶
Bases:
EnumBox structures can be file-based or folder-based.
- FOLDER = 1¶
- FILE = 2¶
- class mail_deduplicate.mail_box.BoxFormat(*values)[source]¶
Bases:
EnumIDs 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
DedupMailfactory.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.
newmay be missing: Thunderbird creates the maildir of a folder withcurandtmponly, asnewholds the mails that no client saw yet. SeensMsgMaildirStore::CreateMaildir()in Thunderbird’s source code.
- mail_deduplicate.mail_box.MH_SEQUENCES = '.mh_sequences'¶
File that holds the sequences of an
MHfolder, likeunseen.Autodetection reads a folder as
MHonly 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
Fromline 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
mboxfile starts with theFromline of its first mail instead, anmmdffile withMMDF_STARTand ababylfile withBABYL_START, none of which matches.
- mail_deduplicate.mail_box.BABYL_START = b'BABYL OPTIONS:'¶
The start of a
babylfile: the first line of its options header.Emacs Rmail writes
BABYL OPTIONS: -*- rmail -*-, and the standard libraryBABYL OPTIONS:alone.
- mail_deduplicate.mail_box.MMDF_START = b'\x01\x01\x01\x01'¶
The start of an
mmdffile: the four Control-A characters that open each mail.
- mail_deduplicate.mail_box.is_mh(path)[source]¶
Returns
Truewhen the path holds theMH_SEQUENCESfile ofMH.- Return type:
- mail_deduplicate.mail_box.is_maildir(path)[source]¶
Returns
Truewhen the path holds the sub-directories of a maildir.- Return type:
- mail_deduplicate.mail_box.holds_cur(path)[source]¶
Returns
Truewhen the path holds thecursub-directory of a maildir.A maildir copied by a tool that skips empty folders, like
git, keeps itscurbut can lose itstmp, whichis_maildir()requires.- Return type:
- mail_deduplicate.mail_box.lacks_new(box)[source]¶
Returns
Truefor a maildir box with nonew, like a Thunderbird folder.- Return type:
- mail_deduplicate.mail_box.contains_maildir(path, test=<function is_maildir>)[source]¶
Returns
Truewhen 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.testtells a maildir apart, withis_maildir()by default.- Return type:
- mail_deduplicate.mail_box.contains_eml(path)[source]¶
Returns
Truewhen the path holds at least one.emlfile, at any depth.Hidden files and directories are ignored, and the extension is matched case-insensitively, mirroring the walk of
EMLboxes.- Return type:
Returns
Truefor 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.msfsummaries of the folders, and the.mozmsgsdirectories where Thunderbird writes files for the search of the operating system. SeensShouldIgnoreFile()in Thunderbird’s source code.- Return type:
- mail_deduplicate.mail_box.is_mbox_file(path)[source]¶
Returns
Truewhen the file holds anmboxbox.An
mboxfile starts with theFromline of its first mail. An empty folder of Thunderbird is an empty file, recognized by the.msfsummary 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:
- mail_deduplicate.mail_box.iter_mbox_files(path)[source]¶
Yields every
mboxfile 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 wholeMaildirectory. Thunderbird keeps the sub-folders of a folder in its<folder>.sbddirectory. The walk skips the names Thunderbird never shows as folders, with all they hold.
- mail_deduplicate.mail_box.contains_mbox(path)[source]¶
Returns
Truewhen the path holds at least onemboxfile, at any depth.- Return type:
- 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_STARTis ababylbox, and one that starts withMMDF_STARTanmmdfbox. A file that starts withMAIL_STARTholds one mail saved alone, as an.emldoes: 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 anmbox, an unreadable one too: opening it then reports the error.- Return type:
- mail_deduplicate.mail_box.profile_lock_held(lock)[source]¶
Returns
Truewhen another process holds the lock file of a profile.On Linux and macOS, Thunderbird holds an
fcntllock 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:
- 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_LOCKfile. A path outside any profile, like an account whose directory was moved out of it, returnsNone.
- 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
babylbox, anmmdfbox or anemlbox of one mail saved alone when it starts like one, and anmboxotherwise: seefile_box_format().A folder takes the first format that fits:
MH, when it holds theMH_SEQUENCESfile.maildir, when it holds theMAILDIR_REQUIRED_SUBDIRSsub-directories, or nested maildir folders at any depth, like the folders of a Thunderbird account of one file per message.eml, when it holds loose.emlfiles.A tree of
mboxboxes, when it holdsmboxfiles at any depth, like the folders of a Thunderbird account.
- Return type:
- 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_formatis provided, forces the opening of the box in the specified format. Else, defaults to autodetection.A directory opened as
mboxgives one box permboxfile of its tree.
- mail_deduplicate.mail_box.lock_box(box, force_unlock)[source]¶
Lock an opened box and allows for forced unlocking.
Returns the locked box. Raises
MailSourceErrorif another lock holds the box andforce_unlockis not set.- Return type:
- 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_sequencesfile that a refusedMH.lock()leaves open.- Return type:
- 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-unlockfor them.Skips box types not supporting subfolders. For
maildir, both theMaildir++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.Maildirlists the mails ofnewandcureach time it refreshes its table of contents, and fails on a missing one. A maildir with nonew, like a Thunderbird folder, getscuralone to list.Maildir.add()would still file a mail in the missingnew, but mails are only added to the boxes a run creates.A directory that holds a
curbut notmpis a maildir that lost its emptytmp, like in agitcopy. Its mails are not read, and a warning names it, at any depth of the tree.
- mail_deduplicate.mail_box.open_mbox_tree(path, force_unlock)[source]¶
Open each
mboxfile 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.lockfile left behind in a Thunderbird account would show up there as a folder.
- mail_deduplicate.mail_box.carry_maildir_metadata(source, key, target, new_key)[source]¶
Give a copied
maildirmail the folder, flags and time of its original.A maildir keeps the state of a mail outside of its content: the
neworcurfolder 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 aMaildirMessagealone, so a mail added as bytes lands innewwith no flags and the time of the run: it is renamed and re-dated afterwards.- Return type:
- mail_deduplicate.mail_box.carry_mh_sequences(source, key, target, new_key)[source]¶
Enroll a copied
MHmail in the sequences of its original.MH keeps the state of a mail (
unseen,replied,flagged) in the.mh_sequencesfile of its folder, by the number of the mail.MH.add()takes them from anMHMessagealone, so they are written here for a mail added as bytes, the wayMH.add()writes them.- Return type:
- 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\rinto 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/1090Line endings are the one conversion left. They are reduced to LF before the write, as every box format but
emlwrites\nas 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 withFrom, as its format requires.The bytes do not include what a format keeps beside each mail: the envelope
Fromline 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 noStatusheader. Babyl labels are not carried, as the standard library takes them from aBabylMessagealone.- Return type: