mailbox —- Manipulate mailboxes in various formats

源代码:Lib/mailbox.py


This module defines two classes, Mailbox and Message, foraccessing 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'sMessage class with format-specific state and behavior.Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.

参见

  • 模块 email
  • Represent and manipulate messages.

Mailbox 对象

  • class mailbox.Mailbox
  • A mailbox, which may be inspected and modified.

The Mailbox class defines an interface and is not intended to beinstantiated. Instead, format-specific subclasses should inherit fromMailbox and your code should instantiate a particular subclass.

The Mailbox interface is dictionary-like, with small keyscorresponding to messages. Keys are issued by the Mailbox instancewith which they will be used and are only meaningful to that Mailboxinstance. A key continues to identify a message even if the correspondingmessage is modified, such as by replacing it with another message.

Messages may be added to a Mailbox instance using the set-likemethod add() and removed using a del statement or the set-likemethods remove() and discard().

Mailbox interface semantics differ from dictionary semantics in somenoteworthy ways. Each time a message is requested, a new representation(typically a Message instance) is generated based upon the currentstate of the mailbox. Similarly, when a message is added to aMailbox instance, the provided message representation's contents arecopied. In neither case is a reference to the message representation kept bythe Mailbox instance.

The default Mailbox iterator iterates over message representations,not keys as the default dictionary iterator does. Moreover, modification of amailbox during iteration is safe and well-defined. Messages added to themailbox after an iterator is created will not be seen by theiterator. Messages removed from the mailbox before the iterator yields themwill be silently skipped, though using a key from an iterator may result in aKeyError exception if the corresponding message is subsequentlyremoved.

警告

Be very cautious when modifying mailboxes that might be simultaneouslychanged by some other process. The safest mailbox format to use for suchtasks is Maildir; try to avoid using single-file formats such as mbox forconcurrent writing. If you're modifying a mailbox, you must lock it bycalling the lock() and unlock() methods before reading anymessages in the file or making any changes by adding or deleting amessage. Failing to lock the mailbox runs the risk of losing messages orcorrupting the entire mailbox.

Mailbox instances have the following methods:

  • add(message)
  • Add message to the mailbox and return the key that has been assigned toit.

Parameter message may be a Message instance, anemail.message.Message instance, a string, a byte string, or afile-like object (which should be open in binary mode). If message isan instance of theappropriate format-specific Message subclass (e.g., if it's anmboxMessage instance and this is an mbox instance), itsformat-specific information is used. Otherwise, reasonable defaults forformat-specific information are used.

在 3.2 版更改: Support for binary input was added.

  • remove(key)
  • delitem(key)
  • discard(key)
  • Delete the message corresponding to key from the mailbox.

If no such message exists, a KeyError exception is raised if themethod was called as remove() or delitem() but noexception is raised if the method was called as discard(). Thebehavior of discard() may be preferred if the underlying mailboxformat supports concurrent modification by other processes.

  • setitem(key, message)
  • Replace the message corresponding to key with message. Raise aKeyError exception if no message already corresponds to key.

As with add(), parameter message may be a Messageinstance, an email.message.Message instance, a string, a bytestring, or a file-like object (which should be open in binary mode). Ifmessage is aninstance of the appropriate format-specific Message subclass(e.g., if it's an mboxMessage instance and this is anmbox instance), its format-specific information isused. Otherwise, the format-specific information of the message thatcurrently corresponds to key is left unchanged.

  • iterkeys()
  • keys()
  • Return an iterator over all keys if called as iterkeys() or return alist of keys if called as keys().

  • itervalues()

  • iter()
  • values()
  • Return an iterator over representations of all messages if called asitervalues() or iter() or return a list of suchrepresentations if called as values(). The messages are representedas instances of the appropriate format-specific Message subclassunless a custom message factory was specified when the Mailboxinstance was initialized.

注解

The behavior of iter() is unlike that of dictionaries, whichiterate over keys.

  • iteritems()
  • items()
  • Return an iterator over (key, message) pairs, where key is a key andmessage is a message representation, if called as iteritems() orreturn a list of such pairs if called as items(). The messages arerepresented as instances of the appropriate format-specificMessage subclass unless a custom message factory was specifiedwhen the Mailbox instance was initialized.

  • get(key, default=None)

  • getitem(key)
  • Return a representation of the message corresponding to key. If no suchmessage exists, default is returned if the method was called asget() and a KeyError exception is raised if the method wascalled as getitem(). The message is represented as an instanceof the appropriate format-specific Message subclass unless acustom message factory was specified when the Mailbox instancewas initialized.

  • getmessage(_key)

  • Return a representation of the message corresponding to key as aninstance of the appropriate format-specific Message subclass, orraise a KeyError exception if no such message exists.

  • getbytes(_key)

  • Return a byte representation of the message corresponding to key, orraise a KeyError exception if no such message exists.

3.2 新版功能.

  • getstring(_key)
  • Return a string representation of the message corresponding to key, orraise a KeyError exception if no such message exists. Themessage is processed through email.message.Message toconvert it to a 7bit clean representation.

  • getfile(_key)

  • Return a file-like representation of the message corresponding to key,or raise a KeyError exception if no such message exists. Thefile-like object behaves as if open in binary mode. This file should beclosed once it is no longer needed.

在 3.2 版更改: The file object really is a binary file; previously it was incorrectlyreturned in text mode. Also, the file-like object now supports thecontext management protocol: you can use a with statement toautomatically close it.

注解

Unlike other representations of messages, file-like representations arenot necessarily independent of the Mailbox instance thatcreated them or of the underlying mailbox. More specific documentationis provided by each subclass.

  • contains(key)
  • Return True if key corresponds to a message, False otherwise.

  • len()

  • Return a count of messages in the mailbox.

  • clear()

  • Delete all messages from the mailbox.

  • pop(key, default=None)

  • Return a representation of the message corresponding to key and deletethe message. If no such message exists, return default. The message isrepresented as an instance of the appropriate format-specificMessage subclass unless a custom message factory was specifiedwhen the Mailbox instance was initialized.

  • popitem()

  • Return an arbitrary (key, message) pair, where key is a key andmessage is a message representation, and delete the correspondingmessage. If the mailbox is empty, raise a KeyError exception. Themessage is represented as an instance of the appropriate format-specificMessage subclass unless a custom message factory was specifiedwhen the Mailbox instance was initialized.

  • update(arg)

  • Parameter arg should be a key-to-message mapping or an iterable of(key, message) pairs. Updates the mailbox so that, for each givenkey and message, the message corresponding to key is set tomessage as if by using setitem(). As with setitem(),each key must already correspond to a message in the mailbox or else aKeyError exception will be raised, so in general it is incorrectfor arg to be a Mailbox instance.

注解

Unlike with dictionaries, keyword arguments are not supported.

  • flush()
  • Write any pending changes to the filesystem. For some Mailboxsubclasses, changes are always written immediately and flush() doesnothing, but you should still make a habit of calling this method.

  • lock()

  • Acquire an exclusive advisory lock on the mailbox so that other processesknow not to modify it. An ExternalClashError is raised if the lockis not available. The particular locking mechanisms used depend upon themailbox format. You should always lock the mailbox before making anymodifications to its contents.

  • unlock()

  • Release the lock on the mailbox, if any.

  • close()

  • Flush the mailbox, unlock it if necessary, and close any open files. Forsome Mailbox subclasses, this method does nothing.

Maildir

  • class mailbox.Maildir(dirname, factory=None, create=True)
  • A subclass of Mailbox for mailboxes in Maildir format. Parameterfactory 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 messagerepresentation. If create is True, the mailbox is created if it does notexist.

If create is True and the dirname path exists, it will be treated asan existing maildir without attempting to verify its directory layout.

It is for historical reasons that dirname is named as such rather than path.

Maildir is a directory-based mailbox format invented for the qmail mailtransfer agent and now widely supported by other programs. Messages in aMaildir mailbox are stored in separate files within a common directorystructure. This design allows Maildir mailboxes to be accessed and modifiedby multiple unrelated programs without data corruption, so file locking isunnecessary.

Maildir mailboxes contain three subdirectories, namely: tmp,new, and cur. Messages are created momentarily in thetmp subdirectory and then moved to the new subdirectory tofinalize delivery. A mail user agent may subsequently move the message to thecur subdirectory and store information about the state of the messagein a special "info" section appended to its file name.

Folders of the style introduced by the Courier mail transfer agent are alsosupported. Any subdirectory of the main mailbox is considered a folder if'.' is the first character in its name. Folder names are represented byMaildir without the leading '.'. Each folder is itself a Maildirmailbox but should not contain other folders. Instead, a logical nesting isindicated using '.' to delimit levels, e.g., "Archived.2005.07".

注解

The Maildir specification requires the use of a colon (':') in certainmessage file names. However, some operating systems do not permit thischaracter in file names, If you wish to use a Maildir-like format on suchan operating system, you should specify another character to useinstead. The exclamation point ('!') is a popular choice. Forexample:

  1. import mailbox
  2. mailbox.Maildir.colon = '!'

The colon attribute may also be set on a per-instance basis.

Maildir instances have all of the methods of Mailbox inaddition to the following:

  • list_folders()
  • Return a list of the names of all folders.

  • getfolder(_folder)

  • Return a Maildir instance representing the folder whose name isfolder. A NoSuchMailboxError exception is raised if the folderdoes not exist.

  • addfolder(_folder)

  • Create a folder whose name is folder and return a Maildirinstance representing it.

  • removefolder(_folder)

  • Delete the folder whose name is folder. If the folder contains anymessages, a NotEmptyError exception will be raised and the folderwill not be deleted.

  • clean()

  • Delete temporary files from the mailbox that have not been accessed in thelast 36 hours. The Maildir specification says that mail-reading programsshould do this occasionally.

Some Mailbox methods implemented by Maildir deserve specialremarks:

  • add(message)
  • setitem(key, message)
  • update(arg)

警告

These methods generate unique file names based upon the current processID. When using multiple threads, undetected name clashes may occur andcause corruption of the mailbox unless threads are coordinated to avoidusing these methods to manipulate the same mailbox simultaneously.

  • flush()
  • All changes to Maildir mailboxes are immediately applied, so this methoddoes nothing.

  • lock()

  • unlock()
  • Maildir mailboxes do not support (or require) locking, so these methods donothing.

  • close()

  • Maildir instances do not keep any open files and the underlyingmailboxes do not support locking, so this method does nothing.

  • getfile(_key)

  • Depending upon the host platform, it may not be possible to modify orremove the underlying message while the returned file remains open.

参见

mbox

  • class mailbox.mbox(path, factory=None, create=True)
  • A subclass of Mailbox for mailboxes in mbox format. Parameter factory_is a callable object that accepts a file-like message representation (whichbehaves as if opened in binary mode) and returns a custom representation. If_factory is None, mboxMessage is used as the default messagerepresentation. If create is True, the mailbox is created if it does notexist.

The mbox format is the classic format for storing mail on Unix systems. Allmessages in an mbox mailbox are stored in a single file with the beginning ofeach message indicated by a line whose first five characters are "From ".

Several variations of the mbox format exist to address perceived shortcomings inthe original. In the interest of compatibility, mbox implements theoriginal format, which is sometimes referred to as mboxo. This means thatthe Content-Length header, if present, is ignored and that anyoccurrences of "From " at the beginning of a line in a message body aretransformed 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 specialremarks:

  • getfile(_key)
  • Using the file after calling flush() or close() on thembox instance may yield unpredictable results or raise anexception.

  • lock()

  • unlock()
  • Three locking mechanisms are used—-dot locking and, if available, theflock() and lockf() system calls.

参见

MH

  • class mailbox.MH(path, factory=None, create=True)
  • A subclass of Mailbox for mailboxes in MH format. Parameter factory_is a callable object that accepts a file-like message representation (whichbehaves as if opened in binary mode) and returns a custom representation. If_factory is None, MHMessage is used as the default messagerepresentation. If create is True, the mailbox is created if it does notexist.

MH is a directory-based mailbox format invented for the MH Message HandlingSystem, a mail user agent. Each message in an MH mailbox resides in its ownfile. An MH mailbox may contain other MH mailboxes (called folders) inaddition to messages. Folders may be nested indefinitely. MH mailboxes alsosupport sequences, which are named lists used to logically groupmessages without moving them to sub-folders. Sequences are defined in a filecalled .mh_sequences in each folder.

The MH class manipulates MH mailboxes, but it does not attempt toemulate all of mh's behaviors. In particular, it does not modifyand is not affected by the context or .mh_profile files thatare used by mh to store its state and configuration.

MH instances have all of the methods of Mailbox in additionto the following:

  • list_folders()
  • Return a list of the names of all folders.

  • getfolder(_folder)

  • Return an MH instance representing the folder whose name isfolder. A NoSuchMailboxError exception is raised if the folderdoes not exist.

  • addfolder(_folder)

  • Create a folder whose name is folder and return an MH instancerepresenting it.

  • removefolder(_folder)

  • Delete the folder whose name is folder. If the folder contains anymessages, a NotEmptyError exception will be raised and the folderwill not be deleted.

  • get_sequences()

  • Return a dictionary of sequence names mapped to key lists. If there are nosequences, the empty dictionary is returned.

  • setsequences(_sequences)

  • Re-define the sequences that exist in the mailbox based upon sequences,a dictionary of names mapped to key lists, like returned byget_sequences().

  • pack()

  • Rename messages in the mailbox as necessary to eliminate gaps innumbering. Entries in the sequences list are updated correspondingly.

注解

Already-issued keys are invalidated by this operation and should not besubsequently used.

Some Mailbox methods implemented by MH deserve specialremarks:

  • remove(key)
  • delitem(key)
  • discard(key)
  • These methods immediately delete the message. The MH convention of markinga message for deletion by prepending a comma to its name is not used.

  • lock()

  • unlock()
  • Three locking mechanisms are used—-dot locking and, if available, theflock() and lockf() system calls. For MH mailboxes, lockingthe mailbox means locking the .mh_sequences file and, only for theduration of any operations that affect them, locking individual messagefiles.

  • getfile(_key)

  • Depending upon the host platform, it may not be possible to remove theunderlying message while the returned file remains open.

  • flush()

  • All changes to MH mailboxes are immediately applied, so this method doesnothing.

  • close()

  • MH instances do not keep any open files, so this method isequivalent to unlock().

参见

Babyl

  • class mailbox.Babyl(path, factory=None, create=True)
  • A subclass of Mailbox for mailboxes in Babyl format. Parameterfactory 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 messagerepresentation. If create is True, the mailbox is created if it does notexist.

Babyl is a single-file mailbox format used by the Rmail mail user agentincluded with Emacs. The beginning of a message is indicated by a linecontaining the two characters Control-Underscore ('\037') and Control-L('\014'). The end of a message is indicated by the start of the nextmessage or, in the case of the last message, a line containing aControl-Underscore ('\037') character.

Messages in a Babyl mailbox have two sets of headers, original headers andso-called visible headers. Visible headers are typically a subset of theoriginal headers that have been reformatted or abridged to be moreattractive. Each message in a Babyl mailbox also has an accompanying list oflabels, or short strings that record extra information about themessage, and a list of all user-defined labels found in the mailbox is keptin the Babyl options section.

Babyl instances have all of the methods of Mailbox inaddition to the following:

  • get_labels()
  • Return a list of the names of all user-defined labels used in the mailbox.

注解

The actual messages are inspected to determine which labels exist inthe mailbox rather than consulting the list of labels in the Babyloptions section, but the Babyl section is updated whenever the mailboxis modified.

Some Mailbox methods implemented by Babyl deserve specialremarks:

  • getfile(_key)
  • In Babyl mailboxes, the headers of a message are not stored contiguouslywith the body of the message. To generate a file-like representation, theheaders and body are copied together into an io.BytesIO instance,which has an API identical to that of afile. As a result, the file-like object is truly independent of theunderlying mailbox but does not save memory compared to a stringrepresentation.

  • lock()

  • unlock()
  • Three locking mechanisms are used—-dot locking and, if available, theflock() and lockf() system calls.

参见

MMDF

  • class mailbox.MMDF(path, factory=None, create=True)
  • A subclass of Mailbox for mailboxes in MMDF format. Parameter factory_is a callable object that accepts a file-like message representation (whichbehaves as if opened in binary mode) and returns a custom representation. If_factory is None, MMDFMessage is used as the default messagerepresentation. If create is True, the mailbox is created if it does notexist.

MMDF is a single-file mailbox format invented for the Multichannel MemorandumDistribution Facility, a mail transfer agent. Each message is in the sameform as an mbox message but is bracketed before and after by lines containingfour Control-A ('\001') characters. As with the mbox format, thebeginning of each message is indicated by a line whose first five charactersare "From ", but additional occurrences of "From " are not transformed to">From " when storing messages because the extra message separator linesprevent mistaking such occurrences for the starts of subsequent messages.

Some Mailbox methods implemented by MMDF deserve specialremarks:

  • getfile(_key)
  • Using the file after calling flush() or close() on theMMDF instance may yield unpredictable results or raise anexception.

  • lock()

  • unlock()
  • Three locking mechanisms are used—-dot locking and, if available, theflock() and lockf() system calls.

参见

  • mmdf man page from tin
  • A specification of MMDF format from the documentation of tin, a newsreader.

  • MMDF

  • A Wikipedia article describing the Multichannel Memorandum DistributionFacility.

Message objects

If message is omitted, the new instance is created in a default, empty state.If message is an email.message.Message instance, its contents arecopied; furthermore, any format-specific information is converted insofar aspossible if message is a Message instance. If message is a string,a byte string,or a file, it should contain an RFC 2822-compliant message, which is readand parsed. Files should be open in binary mode, but text mode filesare accepted for backward compatibility.

The format-specific state and behaviors offered by subclasses vary, but ingeneral it is only the properties that are not specific to a particularmailbox that are supported (although presumably the properties are specificto a particular mailbox format). For example, file offsets for single-filemailbox formats and file names for directory-based mailbox formats are notretained, because they are only applicable to the original mailbox. But statesuch as whether a message has been read by the user or marked as important isretained, because it applies to the message itself.

There is no requirement that Message instances be used to representmessages retrieved using Mailbox instances. In some situations, thetime and memory required to generate Message representations mightnot be acceptable. For such situations, Mailbox instances alsooffer string and file-like representations, and a custom message factory maybe specified when a Mailbox instance is initialized.

MaildirMessage

  • class mailbox.MaildirMessage(message=None)
  • A message with Maildir-specific behaviors. Parameter message has the samemeaning as with the Message constructor.

Typically, a mail user agent application moves all of the messages in thenew subdirectory to the cur subdirectory after the first timethe user opens and closes the mailbox, recording that the messages are oldwhether 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 innew.) 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 maycontain "1," followed by so-called experimental information. Standard flagsfor Maildir messages are as follows:

标志

含义

解释

D

草稿

Under composition

F

已标记

标记为重要

P

已读

转发,重新发送或退回

R

已回复

回复给

S

查看

读取

T

已删除

标记为以后删除

MaildirMessage 实例提供以下方法:

  • get_subdir()
  • Return either "new" (if the message should be stored in the newsubdirectory) or "cur" (if the message should be stored in the cursubdirectory).

注解

A message is typically moved from new to cur after itsmailbox has been accessed, whether or not the message is has beenread. A message msg has been read if "S" in msg.get_flags() isTrue.

  • setsubdir(_subdir)
  • Set the subdirectory the message should be stored in. Parameter _subdir_must be either "new" or "cur".

  • get_flags()

  • Return a string specifying the flags that are currently set. If themessage complies with the standard Maildir format, the result is theconcatenation in alphabetical order of zero or one occurrence of each of'D', 'F', 'P', 'R', 'S', and 'T'. The empty stringis returned if no flags are set or if "info" contains experimentalsemantics.

  • setflags(_flags)

  • Set the flags specified by flags and unset all others.

  • addflag(_flag)

  • Set the flag(s) specified by flag without changing other flags. To addmore than one flag at a time, flag may be a string of more than onecharacter. The current "info" is overwritten whether or not it containsexperimental information rather than flags.

  • removeflag(_flag)

  • Unset the flag(s) specified by flag without changing other flags. Toremove more than one flag at a time, flag maybe a string of more thanone character. If "info" contains experimental information rather thanflags, the current "info" is not modified.

  • get_date()

  • Return the delivery date of the message as a floating-point numberrepresenting seconds since the epoch.

  • setdate(_date)

  • Set the delivery date of the message to date, a floating-point numberrepresenting seconds since the epoch.

  • get_info()

  • Return a string containing the "info" for a message. This is useful foraccessing and modifying "info" that is experimental (i.e., not a list offlags).

  • setinfo(_info)

  • Set "info" to info, which should be a string.

When a MaildirMessage instance is created based upon anmboxMessage or MMDFMessage instance, the Status_and _X-Status headers are omitted and the following conversionstake place:

结果状态mboxMessageMMDFMessage 状态
"cur" 子目录O 标记
F 标记F 标记
R 标记A 标记
S 标记R 标记
T 标记D 标记

When a MaildirMessage instance is created based upon anMHMessage instance, the following conversions take place:

结果状态MHMessage 状态
"cur" 子目录"unseen" 序列
"cur" subdirectory and S flag非 "unseen" 序列
F 标记"flagged" 序列
R 标记"replied" 序列

When a MaildirMessage instance is created based upon aBabylMessage instance, the following conversions take place:

结果状态BabylMessage 状态
"cur" 子目录"unseen" 标签
"cur" subdirectory and S flag非 "unseen" 标签
P 标记"forwarded" 或 "resent" 标签
R 标记"answered" 标签
T 标记"deleted" 标签

mboxMessage

  • class mailbox.mboxMessage(message=None)
  • A message with mbox-specific behaviors. Parameter message has the same meaningas with the Message constructor.

Messages in an mbox mailbox are stored together in a single file. Thesender's envelope address and the time of delivery are typically stored in aline 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 amongmbox implementations. Flags that indicate the state of the message, such aswhether it has been read or marked as important, are typically stored inStatus and X-Status headers.

Conventional flags for mbox messages are as follows:

标志

含义

解释

R

读取

读取

O

Old

以前由MUA检测

D

已删除

标记为以后删除

F

已标记

标记为重要

A

已回复

回复给

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. Theflags and headers typically appear in the order mentioned.

mboxMessage instances offer the following methods:

  • get_from()
  • Return a string representing the "From " line that marks the start of themessage in an mbox mailbox. The leading "From " and the trailing newlineare excluded.

  • setfrom(from_, _time=None_)

  • Set the "From " line to from, which should be specified without aleading "From " or trailing newline. For convenience, _time may bespecified and will be formatted appropriately and appended to from__. If_time is specified, it should be a time.struct_time instance, atuple suitable for passing to time.strftime(), or True (to usetime.gmtime()).

  • get_flags()

  • Return a string specifying the flags that are currently set. If themessage complies with the conventional format, the result is theconcatenation in the following order of zero or one occurrence of each of'R', 'O', 'D', 'F', and 'A'.

  • setflags(_flags)

  • Set the flags specified by flags and unset all others. Parameter _flags_should be the concatenation in any order of zero or more occurrences ofeach of 'R', 'O', 'D', 'F', and 'A'.

  • addflag(_flag)

  • Set the flag(s) specified by flag without changing other flags. To addmore than one flag at a time, flag may be a string of more than onecharacter.

  • removeflag(_flag)

  • Unset the flag(s) specified by flag without changing other flags. Toremove more than one flag at a time, flag maybe a string of more thanone character.

When an mboxMessage instance is created based upon aMaildirMessage instance, a "From " line is generated based upon theMaildirMessage instance's delivery date, and the following conversionstake place:

结果状态MaildirMessage 状态
R 标记S 标记
O 标记"cur" 子目录
D 标记T 标记
F 标记F 标记
A 标记R 标记

When an mboxMessage instance is created based upon anMHMessage instance, the following conversions take place:

结果状态MHMessage 状态
R 标记 和 O 标记非 "unseen" 序列
O 标记"unseen" 序列
F 标记"flagged" 序列
A 标记"replied" 序列

When an mboxMessage instance is created based upon aBabylMessage instance, the following conversions take place:

结果状态BabylMessage 状态
R 标记 和 O 标记非 "unseen" 标签
O 标记"unseen" 标签
D 标记"deleted" 标签
A 标记"answered" 标签

When a Message instance is created based upon an MMDFMessageinstance, the "From " line is copied and all flags directly correspond:

结果状态MMDFMessage 状态
R 标记R 标记
O 标记O 标记
D 标记D 标记
F 标记F 标记
A 标记A 标记

MHMessage

  • class mailbox.MHMessage(message=None)
  • A message with MH-specific behaviors. Parameter message has the same meaningas with the Message constructor.

MH messages do not support marks or flags in the traditional sense, but theydo support sequences, which are logical groupings of arbitrary messages. Somemail reading programs (although not the standard mh andnmh) use sequences in much the same way flags are used with otherformats, as follows:

序列

解释

未读

未读取,但先前被MUA检测到

已回复

回复给

已标记

标记为重要

MHMessage instances offer the following methods:

  • get_sequences()
  • Return a list of the names of sequences that include this message.

  • setsequences(_sequences)

  • Set the list of sequences that include this message.

  • addsequence(_sequence)

  • Add sequence to the list of sequences that include this message.

  • removesequence(_sequence)

  • Remove sequence from the list of sequences that include this message.

When an MHMessage instance is created based upon aMaildirMessage instance, the following conversions take place:

结果状态MaildirMessage 状态
"unseen" 序列非 S 标记
"replied" 序列R 标记
"flagged" 序列F 标记

When an MHMessage instance is created based upon anmboxMessage or MMDFMessage instance, the Status_and _X-Status headers are omitted and the following conversionstake place:

结果状态mboxMessageMMDFMessage 状态
"unseen" 序列非 R 标记
"replied" 序列A 标记
"flagged" 序列F 标记

When an MHMessage instance is created based upon aBabylMessage instance, the following conversions take place:

结果状态BabylMessage 状态
"unseen" 序列"unseen" 标签
"replied" 序列"answered" 标签

BabylMessage

  • class mailbox.BabylMessage(message=None)
  • A message with Babyl-specific behaviors. Parameter message has the samemeaning as with the Message constructor.

Certain message labels, called attributes, are defined by conventionto have special meanings. The attributes are as follows:

标签

解释

未读

未读取,但先前被MUA检测到

deleted

标记为以后删除

filed

复制到另一个文件或邮箱

answered

回复给

forwarded

已转发

edited

由用户修改

resent

已重发

By default, Rmail displays only visible headers. The BabylMessageclass, though, uses the original headers because they are morecomplete. Visible headers may be accessed explicitly if desired.

BabylMessage instances offer the following methods:

  • get_labels()
  • 返回邮件上的标签列表。

  • setlabels(_labels)

  • 将消息上的标签列表设置为 labels

  • addlabel(_label)

  • label 添加到消息上的标签列表中。

  • removelabel(_label)

  • 从消息上的标签列表中删除 label

  • get_visible()

  • Return an Message instance whose headers are the message'svisible headers and whose body is empty.

  • setvisible(_visible)

  • Set the message's visible headers to be the same as the headers inmessage. Parameter visible should be a Message instance, anemail.message.Message instance, a string, or a file-like object(which should be open in text mode).

  • update_visible()

  • When a BabylMessage instance's original headers are modified, thevisible headers are not automatically modified to correspond. This methodupdates the visible headers as follows: each visible header with acorresponding original header is set to the value of the original header,each visible header without a corresponding original header is removed,and any of Date, From, Reply-To,To, CC, and Subject that arepresent in the original headers but not the visible headers are added tothe visible headers.

When a BabylMessage instance is created based upon aMaildirMessage instance, the following conversions take place:

结果状态MaildirMessage 状态
"unseen" 标签非 S 标记
"deleted" 标签T 标记
"answered" 标签R 标记
"forwarded" 标签P 标记

When a BabylMessage instance is created based upon anmboxMessage or MMDFMessage instance, the Status_and _X-Status headers are omitted and the following conversionstake place:

结果状态mboxMessageMMDFMessage 状态
"unseen" 标签非 R 标记
"deleted" 标签D 标记
"answered" 标签A 标记

When a BabylMessage instance is created based upon anMHMessage instance, the following conversions take place:

结果状态MHMessage 状态
"unseen" 标签"unseen" 序列
"answered" 标签"replied" 序列

MMDFMessage

  • class mailbox.MMDFMessage(message=None)
  • A message with MMDF-specific behaviors. Parameter message has the same meaningas with the Message constructor.

As with message in an mbox mailbox, MMDF messages are stored with thesender's address and the delivery date in an initial line beginning with"From ". Likewise, flags that indicate the state of the message aretypically stored in Status and X-Status headers.

Conventional flags for MMDF messages are identical to those of mbox messageand are as follows:

标志

含义

解释

R

读取

读取

O

Old

以前由MUA检测

D

已删除

标记为以后删除

F

已标记

标记为重要

A

已回复

回复给

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. Theflags and headers typically appear in the order mentioned.

MMDFMessage instances offer the following methods, which areidentical to those offered by mboxMessage:

  • get_from()
  • Return a string representing the "From " line that marks the start of themessage in an mbox mailbox. The leading "From " and the trailing newlineare excluded.

  • setfrom(from_, _time=None_)

  • Set the "From " line to from, which should be specified without aleading "From " or trailing newline. For convenience, _time may bespecified and will be formatted appropriately and appended to from__. If_time is specified, it should be a time.struct_time instance, atuple suitable for passing to time.strftime(), or True (to usetime.gmtime()).

  • get_flags()

  • Return a string specifying the flags that are currently set. If themessage complies with the conventional format, the result is theconcatenation in the following order of zero or one occurrence of each of'R', 'O', 'D', 'F', and 'A'.

  • setflags(_flags)

  • Set the flags specified by flags and unset all others. Parameter _flags_should be the concatenation in any order of zero or more occurrences ofeach of 'R', 'O', 'D', 'F', and 'A'.

  • addflag(_flag)

  • Set the flag(s) specified by flag without changing other flags. To addmore than one flag at a time, flag may be a string of more than onecharacter.

  • removeflag(_flag)

  • Unset the flag(s) specified by flag without changing other flags. Toremove more than one flag at a time, flag maybe a string of more thanone character.

When an MMDFMessage instance is created based upon aMaildirMessage instance, a "From " line is generated based upon theMaildirMessage instance's delivery date, and the following conversionstake place:

结果状态MaildirMessage 状态
R 标记S 标记
O 标记"cur" 子目录
D 标记T 标记
F 标记F 标记
A 标记R 标记

When an MMDFMessage instance is created based upon anMHMessage instance, the following conversions take place:

结果状态MHMessage 状态
R 标记 和 O 标记非 "unseen" 序列
O 标记"unseen" 序列
F 标记"flagged" 序列
A 标记"replied" 序列

When an MMDFMessage instance is created based upon aBabylMessage instance, the following conversions take place:

结果状态BabylMessage 状态
R 标记 和 O 标记非 "unseen" 标签
O 标记"unseen" 标签
D 标记"deleted" 标签
A 标记"answered" 标签

When an MMDFMessage instance is created based upon anmboxMessage instance, the "From " line is copied and all flags directlycorrespond:

结果状态mboxMessage 状态
R 标记R 标记
O 标记O 标记
D 标记D 标记
F 标记F 标记
A 标记A 标记

异常

The following exception classes are defined in the mailbox module:

  • exception mailbox.Error
  • The based class for all other module-specific exceptions.
  • exception mailbox.NoSuchMailboxError
  • Raised when a mailbox is expected but is not found, such as when instantiating aMailbox subclass with a path that does not exist (and with the _create_parameter set to False), or when opening a folder that does not exist.
  • exception mailbox.NotEmptyError
  • Raised when a mailbox is not empty but is expected to be, such as when deletinga folder that contains messages.
  • exception mailbox.ExternalClashError
  • Raised when some mailbox-related condition beyond the control of the programcauses it to be unable to proceed, such as when failing to acquire a lock thatanother program already holds a lock, or when a uniquely-generated file namealready exists.
  • exception mailbox.FormatError
  • Raised when the data in a file cannot be parsed, such as when an MHinstance attempts to read a corrupted .mh_sequences file.

例子

A simple example of printing the subjects of all messages in a mailbox that seeminteresting:

  1. import mailbox
  2. for message in mailbox.mbox('~/mbox'):
  3. subject = message['subject'] # Could possibly be None.
  4. if subject and 'python' in subject.lower():
  5. print(subject)

To copy all mail from a Babyl mailbox to an MH mailbox, converting all of theformat-specific information that can be converted:

  1. import mailbox
  2. destination = mailbox.MH('~/Mail')
  3. destination.lock()
  4. for message in mailbox.Babyl('~/RMAIL'):
  5. destination.add(mailbox.MHMessage(message))
  6. destination.flush()
  7. destination.unlock()

This example sorts mail from several mailing lists into different mailboxes,being careful to avoid mail corruption due to concurrent modification by otherprograms, mail loss due to interruption of the program, or premature terminationdue to malformed messages in the mailbox:

  1. import mailbox
  2. import email.errors
  3.  
  4. list_names = ('python-list', 'python-dev', 'python-bugs')
  5.  
  6. boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names}
  7. inbox = mailbox.Maildir('~/Maildir', factory=None)
  8.  
  9. for key in inbox.iterkeys():
  10. try:
  11. message = inbox[key]
  12. except email.errors.MessageParseError:
  13. continue # The message is malformed. Just leave it.
  14.  
  15. for name in list_names:
  16. list_id = message['list-id']
  17. if list_id and name in list_id:
  18. # Get mailbox to use
  19. box = boxes[name]
  20.  
  21. # Write copy to disk before removing original.
  22. # If there's a crash, you might duplicate a message, but
  23. # that's better than losing a message completely.
  24. box.lock()
  25. box.add(message)
  26. box.flush()
  27. box.unlock()
  28.  
  29. # Remove original message
  30. inbox.lock()
  31. inbox.discard(key)
  32. inbox.flush()
  33. inbox.unlock()
  34. break # Found destination, so stop looking.
  35.  
  36. for box in boxes.itervalues():
  37. box.close()