This module defines two classes, Mailbox and Message, for accessing and manipulating on-disk mailboxes and the messages they contain. Mailbox offers a dictionary-like mapping from keys to messages. Message extends the email.Message module’s Message class with format-specific state and behavior. Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
See also
A mailbox, which may be inspected and modified.
The Mailbox class defines an interface and is not intended to be instantiated. Instead, format-specific subclasses should inherit from Mailbox and your code should instantiate a particular subclass.
The Mailbox interface is dictionary-like, with small keys corresponding to messages. Keys are issued by the Mailbox instance with which they will be used and are only meaningful to that Mailbox instance. A key continues to identify a message even if the corresponding message is modified, such as by replacing it with another message.
Messages may be added to a Mailbox instance using the set-like method add() and removed using a del statement or the set-like methods remove() and discard().
Mailbox interface semantics differ from dictionary semantics in some noteworthy ways. Each time a message is requested, a new representation (typically a Message instance) is generated based upon the current state of the mailbox. Similarly, when a message is added to a Mailbox instance, the provided message representation’s contents are copied. In neither case is a reference to the message representation kept by the Mailbox instance.
The default Mailbox iterator iterates over message representations, not keys as the default dictionary iterator does. Moreover, modification of a mailbox during iteration is safe and well-defined. Messages added to the mailbox after an iterator is created will not be seen by the iterator. Messages removed from the mailbox before the iterator yields them will be silently skipped, though using a key from an iterator may result in a KeyError exception if the corresponding message is subsequently removed.
Warning
Be very cautious when modifying mailboxes that might be simultaneously changed by some other process. The safest mailbox format to use for such tasks is Maildir; try to avoid using single-file formats such as mbox for concurrent writing. If you’re modifying a mailbox, you must lock it by calling the lock() and unlock() methods before reading any messages in the file or making any changes by adding or deleting a message. Failing to lock the mailbox runs the risk of losing messages or corrupting the entire mailbox.
Mailbox instances have the following methods:
Add message to the mailbox and return the key that has been assigned to it.
Parameter message may be a Message instance, an email.Message.Message instance, a string, or a file-like object (which should be open in text mode). If message is an instance of the appropriate format-specific Message subclass (e.g., if it’s an mboxMessage instance and this is an mbox instance), its format-specific information is used. Otherwise, reasonable defaults for format-specific information are used.
Delete the message corresponding to key from the mailbox.
If no such message exists, a KeyError exception is raised if the method was called as remove() or __delitem__() but no exception is raised if the method was called as discard(). The behavior of discard() may be preferred if the underlying mailbox format supports concurrent modification by other processes.
Replace the message corresponding to key with message. Raise a KeyError exception if no message already corresponds to key.
As with add(), parameter message may be a Message instance, an email.Message.Message instance, a string, or a file-like object (which should be open in text mode). If message is an instance of the appropriate format-specific Message subclass (e.g., if it’s an mboxMessage instance and this is an mbox instance), its format-specific information is used. Otherwise, the format-specific information of the message that currently corresponds to key is left unchanged.
Return an iterator over representations of all messages if called as itervalues() or __iter__() or return a list of such representations if called as values(). The messages are represented as instances of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized.
Note
The behavior of __iter__() is unlike that of dictionaries, which iterate over keys.
Return a file-like representation of the message corresponding to key, or raise a KeyError exception if no such message exists. The file-like object behaves as if open in binary mode. This file should be closed once it is no longer needed.
Note
Unlike other representations of messages, file-like representations are not necessarily independent of the Mailbox instance that created them or of the underlying mailbox. More specific documentation is provided by each subclass.
Parameter arg should be a key-to-message mapping or an iterable of (key, message) pairs. Updates the mailbox so that, for each given key and message, the message corresponding to key is set to message as if by using __setitem__(). As with __setitem__(), each key must already correspond to a message in the mailbox or else a KeyError exception will be raised, so in general it is incorrect for arg to be a Mailbox instance.
Note
Unlike with dictionaries, keyword arguments are not supported.
A subclass of Mailbox for mailboxes in Maildir format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MaildirMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
It is for historical reasons that factory defaults to rfc822.Message and that dirname is named as such rather than path. For a Maildir instance that behaves like instances of other Mailbox subclasses, set factory to None.
Maildir is a directory-based mailbox format invented for the qmail mail transfer agent and now widely supported by other programs. Messages in a Maildir mailbox are stored in separate files within a common directory structure. This design allows Maildir mailboxes to be accessed and modified by multiple unrelated programs without data corruption, so file locking is unnecessary.
Maildir mailboxes contain three subdirectories, namely: tmp, new, and cur. Messages are created momentarily in the tmp subdirectory and then moved to the new subdirectory to finalize delivery. A mail user agent may subsequently move the message to the cur subdirectory and store information about the state of the message in a special “info” section appended to its file name.
Folders of the style introduced by the Courier mail transfer agent are also supported. Any subdirectory of the main mailbox is considered a folder if '.' is the first character in its name. Folder names are represented by Maildir without the leading '.'. Each folder is itself a Maildir mailbox but should not contain other folders. Instead, a logical nesting is indicated using '.' to delimit levels, e.g., “Archived.2005.07”.
Note
The Maildir specification requires the use of a colon (':') in certain message file names. However, some operating systems do not permit this character in file names, If you wish to use a Maildir-like format on such an operating system, you should specify another character to use instead. The exclamation point ('!') is a popular choice. For example:
import mailbox
mailbox.Maildir.colon = '!'
The colon attribute may also be set on a per-instance basis.
Maildir instances have all of the methods of Mailbox in addition to the following:
Some Mailbox methods implemented by Maildir deserve special remarks:
Warning
These methods generate unique file names based upon the current process ID. When using multiple threads, undetected name clashes may occur and cause corruption of the mailbox unless threads are coordinated to avoid using these methods to manipulate the same mailbox simultaneously.
See also
A subclass of Mailbox for mailboxes in mbox format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, mboxMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
The mbox format is the classic format for storing mail on Unix systems. All messages in an mbox mailbox are stored in a single file with the beginning of each message indicated by a line whose first five characters are “From “.
Several variations of the mbox format exist to address perceived shortcomings in the original. In the interest of compatibility, mbox implements the original format, which is sometimes referred to as mboxo. This means that the Content-Length header, if present, is ignored and that any occurrences of “From ” at the beginning of a line in a message body are transformed to “>From ” when storing the message, although occurrences of “>From ” are not transformed to “From ” when reading the message.
Some Mailbox methods implemented by mbox deserve special remarks:
See also
A subclass of Mailbox for mailboxes in MH format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MHMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
MH is a directory-based mailbox format invented for the MH Message Handling System, a mail user agent. Each message in an MH mailbox resides in its own file. An MH mailbox may contain other MH mailboxes (called folders) in addition to messages. Folders may be nested indefinitely. MH mailboxes also support sequences, which are named lists used to logically group messages without moving them to sub-folders. Sequences are defined in a file called .mh_sequences in each folder.
The MH class manipulates MH mailboxes, but it does not attempt to emulate all of mh‘s behaviors. In particular, it does not modify and is not affected by the context or .mh_profile files that are used by mh to store its state and configuration.
MH instances have all of the methods of Mailbox in addition to the following:
Rename messages in the mailbox as necessary to eliminate gaps in numbering. Entries in the sequences list are updated correspondingly.
Note
Already-issued keys are invalidated by this operation and should not be subsequently used.
Some Mailbox methods implemented by MH deserve special remarks:
See also
A subclass of Mailbox for mailboxes in Babyl format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, BabylMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
Babyl is a single-file mailbox format used by the Rmail mail user agent included with Emacs. The beginning of a message is indicated by a line containing the two characters Control-Underscore ('\037') and Control-L ('\014'). The end of a message is indicated by the start of the next message or, in the case of the last message, a line containing a Control-Underscore ('\037') character.
Messages in a Babyl mailbox have two sets of headers, original headers and so-called visible headers. Visible headers are typically a subset of the original headers that have been reformatted or abridged to be more attractive. Each message in a Babyl mailbox also has an accompanying list of labels, or short strings that record extra information about the message, and a list of all user-defined labels found in the mailbox is kept in the Babyl options section.
Babyl instances have all of the methods of Mailbox in addition to the following:
Return a list of the names of all user-defined labels used in the mailbox.
Note
The actual messages are inspected to determine which labels exist in the mailbox rather than consulting the list of labels in the Babyl options section, but the Babyl section is updated whenever the mailbox is modified.
Some Mailbox methods implemented by Babyl deserve special remarks:
See also
A subclass of Mailbox for mailboxes in MMDF format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MMDFMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
MMDF is a single-file mailbox format invented for the Multichannel Memorandum Distribution Facility, a mail transfer agent. Each message is in the same form as an mbox message but is bracketed before and after by lines containing four Control-A ('\001') characters. As with the mbox format, the beginning of each message is indicated by a line whose first five characters are “From “, but additional occurrences of “From ” are not transformed to “>From ” when storing messages because the extra message separator lines prevent mistaking such occurrences for the starts of subsequent messages.
Some Mailbox methods implemented by MMDF deserve special remarks:
See also
A subclass of the email.Message module’s Message. Subclasses of mailbox.Message add mailbox-format-specific state and behavior.
If message is omitted, the new instance is created in a default, empty state. If message is an email.Message.Message instance, its contents are copied; furthermore, any format-specific information is converted insofar as possible if message is a Message instance. If message is a string or a file, it should contain an RFC 2822-compliant message, which is read and parsed.
The format-specific state and behaviors offered by subclasses vary, but in general it is only the properties that are not specific to a particular mailbox that are supported (although presumably the properties are specific to a particular mailbox format). For example, file offsets for single-file mailbox formats and file names for directory-based mailbox formats are not retained, because they are only applicable to the original mailbox. But state such as whether a message has been read by the user or marked as important is retained, because it applies to the message itself.
There is no requirement that Message instances be used to represent messages retrieved using Mailbox instances. In some situations, the time and memory required to generate Message representations might not not acceptable. For such situations, Mailbox instances also offer string and file-like representations, and a custom message factory may be specified when a Mailbox instance is initialized.
A message with Maildir-specific behaviors. Parameter message has the same meaning as with the Message constructor.
Typically, a mail user agent application moves all of the messages in the new subdirectory to the cur subdirectory after the first time the user opens and closes the mailbox, recording that the messages are old whether or not they’ve actually been read. Each message in cur has an “info” section added to its file name to store information about its state. (Some mail readers may also add an “info” section to messages in new.) The “info” section may take one of two forms: it may contain “2,” followed by a list of standardized flags (e.g., “2,FR”) or it may contain “1,” followed by so-called experimental information. Standard flags for Maildir messages are as follows:
Flag | Meaning | Explanation |
---|---|---|
D | Draft | Under composition |
F | Flagged | Marked as important |
P | Passed | Forwarded, resent, or bounced |
R | Replied | Replied to |
S | Seen | Read |
T | Trashed | Marked for subsequent deletion |
MaildirMessage instances offer the following methods:
Return either “new” (if the message should be stored in the new subdirectory) or “cur” (if the message should be stored in the cur subdirectory).
Note
A message is typically moved from new to cur after its mailbox has been accessed, whether or not the message is has been read. A message msg has been read if "S" in msg.get_flags() is True.
When a MaildirMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place:
Resulting state | mboxMessage or MMDFMessage state |
---|---|
“cur” subdirectory | O flag |
F flag | F flag |
R flag | A flag |
S flag | R flag |
T flag | D flag |
When a MaildirMessage instance is created based upon an MHMessage instance, the following conversions take place:
Resulting state | MHMessage state |
---|---|
“cur” subdirectory | “unseen” sequence |
“cur” subdirectory and S flag | no “unseen” sequence |
F flag | “flagged” sequence |
R flag | “replied” sequence |
When a MaildirMessage instance is created based upon a BabylMessage instance, the following conversions take place:
Resulting state | BabylMessage state |
---|---|
“cur” subdirectory | “unseen” label |
“cur” subdirectory and S flag | no “unseen” label |
P flag | “forwarded” or “resent” label |
R flag | “answered” label |
T flag | “deleted” label |
A message with mbox-specific behaviors. Parameter message has the same meaning as with the Message constructor.
Messages in an mbox mailbox are stored together in a single file. The sender’s envelope address and the time of delivery are typically stored in a line beginning with “From ” that is used to indicate the start of a message, though there is considerable variation in the exact format of this data among mbox implementations. Flags that indicate the state of the message, such as whether it has been read or marked as important, are typically stored in Status and X-Status headers.
Conventional flags for mbox messages are as follows:
Flag | Meaning | Explanation |
---|---|---|
R | Read | Read |
O | Old | Previously detected by MUA |
D | Deleted | Marked for subsequent deletion |
F | Flagged | Marked as important |
A | Answered | Replied to |
The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned.
mboxMessage instances offer the following methods:
When an mboxMessage instance is created based upon a MaildirMessage instance, a “From ” line is generated based upon the MaildirMessage instance’s delivery date, and the following conversions take place:
Resulting state | MaildirMessage state |
---|---|
R flag | S flag |
O flag | “cur” subdirectory |
D flag | T flag |
F flag | F flag |
A flag | R flag |
When an mboxMessage instance is created based upon an MHMessage instance, the following conversions take place:
Resulting state | MHMessage state |
---|---|
R flag and O flag | no “unseen” sequence |
O flag | “unseen” sequence |
F flag | “flagged” sequence |
A flag | “replied” sequence |
When an mboxMessage instance is created based upon a BabylMessage instance, the following conversions take place:
Resulting state | BabylMessage state |
---|---|
R flag and O flag | no “unseen” label |
O flag | “unseen” label |
D flag | “deleted” label |
A flag | “answered” label |
When a Message instance is created based upon an MMDFMessage instance, the “From ” line is copied and all flags directly correspond:
Resulting state | MMDFMessage state |
---|---|
R flag | R flag |
O flag | O flag |
D flag | D flag |
F flag | F flag |
A flag | A flag |
A message with MH-specific behaviors. Parameter message has the same meaning as with the Message constructor.
MH messages do not support marks or flags in the traditional sense, but they do support sequences, which are logical groupings of arbitrary messages. Some mail reading programs (although not the standard mh and nmh) use sequences in much the same way flags are used with other formats, as follows:
Sequence | Explanation |
---|---|
unseen | Not read, but previously detected by MUA |
replied | Replied to |
flagged | Marked as important |
MHMessage instances offer the following methods:
When an MHMessage instance is created based upon a MaildirMessage instance, the following conversions take place:
Resulting state | MaildirMessage state |
---|---|
“unseen” sequence | no S flag |
“replied” sequence | R flag |
“flagged” sequence | F flag |
When an MHMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place:
Resulting state | mboxMessage or MMDFMessage state |
---|---|
“unseen” sequence | no R flag |
“replied” sequence | A flag |
“flagged” sequence | F flag |
When an MHMessage instance is created based upon a BabylMessage instance, the following conversions take place:
Resulting state | BabylMessage state |
---|---|
“unseen” sequence | “unseen” label |
“replied” sequence | “answered” label |
A message with Babyl-specific behaviors. Parameter message has the same meaning as with the Message constructor.
Certain message labels, called attributes, are defined by convention to have special meanings. The attributes are as follows:
Label | Explanation |
---|---|
unseen | Not read, but previously detected by MUA |
deleted | Marked for subsequent deletion |
filed | Copied to another file or mailbox |
answered | Replied to |
forwarded | Forwarded |
edited | Modified by the user |
resent | Resent |
By default, Rmail displays only visible headers. The BabylMessage class, though, uses the original headers because they are more complete. Visible headers may be accessed explicitly if desired.
BabylMessage instances offer the following methods:
When a BabylMessage instance is created based upon a MaildirMessage instance, the following conversions take place:
Resulting state | MaildirMessage state |
---|---|
“unseen” label | no S flag |
“deleted” label | T flag |
“answered” label | R flag |
“forwarded” label | P flag |
When a BabylMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place:
Resulting state | mboxMessage or MMDFMessage state |
---|---|
“unseen” label | no R flag |
“deleted” label | D flag |
“answered” label | A flag |
When a BabylMessage instance is created based upon an MHMessage instance, the following conversions take place:
Resulting state | MHMessage state |
---|---|
“unseen” label | “unseen” sequence |
“answered” label | “replied” sequence |
A message with MMDF-specific behaviors. Parameter message has the same meaning as with the Message constructor.
As with message in an mbox mailbox, MMDF messages are stored with the sender’s address and the delivery date in an initial line beginning with “From “. Likewise, flags that indicate the state of the message are typically stored in Status and X-Status headers.
Conventional flags for MMDF messages are identical to those of mbox message and are as follows:
Flag | Meaning | Explanation |
---|---|---|
R | Read | Read |
O | Old | Previously detected by MUA |
D | Deleted | Marked for subsequent deletion |
F | Flagged | Marked as important |
A | Answered | Replied to |
The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned.
MMDFMessage instances offer the following methods, which are identical to those offered by mboxMessage:
When an MMDFMessage instance is created based upon a MaildirMessage instance, a “From ” line is generated based upon the MaildirMessage instance’s delivery date, and the following conversions take place:
Resulting state | MaildirMessage state |
---|---|
R flag | S flag |
O flag | “cur” subdirectory |
D flag | T flag |
F flag | F flag |
A flag | R flag |
When an MMDFMessage instance is created based upon an MHMessage instance, the following conversions take place:
Resulting state | MHMessage state |
---|---|
R flag and O flag | no “unseen” sequence |
O flag | “unseen” sequence |
F flag | “flagged” sequence |
A flag | “replied” sequence |
When an MMDFMessage instance is created based upon a BabylMessage instance, the following conversions take place:
Resulting state | BabylMessage state |
---|---|
R flag and O flag | no “unseen” label |
O flag | “unseen” label |
D flag | “deleted” label |
A flag | “answered” label |
When an MMDFMessage instance is created based upon an mboxMessage instance, the “From ” line is copied and all flags directly correspond:
Resulting state | mboxMessage state |
---|---|
R flag | R flag |
O flag | O flag |
D flag | D flag |
F flag | F flag |
A flag | A flag |
The following exception classes are defined in the mailbox module:
Deprecated since version 2.6.
Older versions of the mailbox module do not support modification of mailboxes, such as adding or removing message, and do not provide classes to represent format-specific message properties. For backward compatibility, the older mailbox classes are still available, but the newer classes should be used in preference to them. The old classes will be removed in Python 3.0.
Older mailbox objects support only iteration and provide a single public method:
Most of the older mailbox classes have names that differ from the current mailbox class names, except for Maildir. For this reason, the new Maildir class defines a next() method and its constructor differs slightly from those of the other new mailbox classes.
The older mailbox classes whose names are not the same as their newer counterparts are as follows:
Access to a classic Unix-style mailbox, where all messages are contained in a single file and separated by From (a.k.a. From_) lines. The file object fp points to the mailbox file. The optional factory parameter is a callable that should create new message objects. factory is called with one argument, fp by the next() method of the mailbox object. The default is the rfc822.Message class (see the rfc822 module – and the note below).
Note
For reasons of this module’s internal implementation, you will probably want to open the fp object in binary mode. This is especially important on Windows.
For maximum portability, messages in a Unix-style mailbox are separated by any line that begins exactly with the string 'From ' (note the trailing space) if preceded by exactly two newlines. Because of the wide-range of variations in practice, nothing else on the From_ line should be considered. However, the current implementation doesn’t check for the leading two newlines. This is usually fine for most applications.
The UnixMailbox class implements a more strict version of From_ line checking, using a regular expression that usually correctly matched From_ delimiters. It considers delimiter line to be separated by From name time lines. For maximum portability, use the PortableUnixMailbox class instead. This class is identical to UnixMailbox except that individual messages are separated by only From lines.
If you wish to use the older mailbox classes with the email module rather than the deprecated rfc822 module, you can do so as follows:
import email
import email.Errors
import mailbox
def msgfactory(fp):
try:
return email.message_from_file(fp)
except email.Errors.MessageParseError:
# Don't return None since that will
# stop the mailbox iterator
return ''
mbox = mailbox.UnixMailbox(fp, msgfactory)
Alternatively, if you know your mailbox contains only well-formed MIME messages, you can simplify this to:
import email
import mailbox
mbox = mailbox.UnixMailbox(fp, email.message_from_file)
A simple example of printing the subjects of all messages in a mailbox that seem interesting:
import mailbox
for message in mailbox.mbox('~/mbox'):
subject = message['subject'] # Could possibly be None.
if subject and 'python' in subject.lower():
print subject
To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the format-specific information that can be converted:
import mailbox
destination = mailbox.MH('~/Mail')
destination.lock()
for message in mailbox.Babyl('~/RMAIL'):
destination.add(mailbox.MHMessage(message))
destination.flush()
destination.unlock()
This example sorts mail from several mailing lists into different mailboxes, being careful to avoid mail corruption due to concurrent modification by other programs, mail loss due to interruption of the program, or premature termination due to malformed messages in the mailbox:
import mailbox
import email.Errors
list_names = ('python-list', 'python-dev', 'python-bugs')
boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names)
inbox = mailbox.Maildir('~/Maildir', factory=None)
for key in inbox.iterkeys():
try:
message = inbox[key]
except email.Errors.MessageParseError:
continue # The message is malformed. Just leave it.
for name in list_names:
list_id = message['list-id']
if list_id and name in list_id:
# Get mailbox to use
box = boxes[name]
# Write copy to disk before removing original.
# If there's a crash, you might duplicate a message, but
# that's better than losing a message completely.
box.lock()
box.add(message)
box.flush()
box.unlock()
# Remove original message
inbox.lock()
inbox.discard(key)
inbox.flush()
inbox.unlock()
break # Found destination, so stop looking.
for box in boxes.itervalues():
box.close()