mailbox --- 以各種格式操作郵件信箱¶
原始碼:Lib/mailbox.py
This module defines two classes,Mailbox andMessage, foraccessing and manipulating on-disk mailboxes and the messages they contain.Mailbox offers a dictionary-like mapping from keys to messages.Message extends theemail.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 物件¶
- classmailbox.Mailbox¶
A mailbox, which may be inspected and modified.
The
Mailboxclass defines an interface and is not intended to beinstantiated. Instead, format-specific subclasses should inherit fromMailboxand your code should instantiate a particular subclass.The
Mailboxinterface is dictionary-like, with small keyscorresponding to messages. Keys are issued by theMailboxinstancewith which they will be used and are only meaningful to thatMailboxinstance. 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
Mailboxinstance using the set-likemethodadd()and removed using adelstatement or the set-likemethodsremove()anddiscard().Mailboxinterface semantics differ from dictionary semantics in somenoteworthy ways. Each time a message is requested, a new representation(typically aMessageinstance) is generated based upon the currentstate of the mailbox. Similarly, when a message is added to aMailboxinstance, the provided message representation's contents arecopied. In neither case is a reference to the message representation kept bytheMailboxinstance.The default
Mailboxiterator iterates over messagerepresentations, not keys as the defaultdictionaryiterator 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 aKeyErrorexception 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 asmboxforconcurrent writing. If you're modifying a mailbox, youmust lock it bycalling thelock()andunlock()methodsbefore 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.Mailboxinstances have the following methods:- add(message)¶
Addmessage to the mailbox and return the key that has been assigned toit.
Parametermessage may be a
Messageinstance, anemail.message.Messageinstance, a string, a byte string, or afile-like object (which should be open in binary mode). Ifmessage isan instance of theappropriate format-specificMessagesubclass (e.g., if it's anmboxMessageinstance and this is anmboxinstance), 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 tokey from the mailbox.
If no such message exists, a
KeyErrorexception is raised if themethod was called asremove()or__delitem__()but noexception is raised if the method was called asdiscard(). Thebehavior ofdiscard()may be preferred if the underlying mailboxformat supports concurrent modification by other processes.
- __setitem__(key,message)¶
Replace the message corresponding tokey withmessage. Raise a
KeyErrorexception if no message already corresponds tokey.As with
add(), parametermessage may be aMessageinstance, anemail.message.Messageinstance, a string, a bytestring, or a file-like object (which should be open in binary mode). Ifmessage is aninstance of the appropriate format-specificMessagesubclass(e.g., if it's anmboxMessageinstance and this is anmboxinstance), its format-specific information isused. Otherwise, the format-specific information of the message thatcurrently corresponds tokey is left unchanged.
- keys()¶
The same as
iterkeys(), except that alistis returnedrather than aniterator
- itervalues()¶
- __iter__()¶
Return aniterator over representations of all messages.The messages are representedas instances of the appropriate format-specific
Messagesubclassunless a custom message factory was specified when theMailboxinstance was initialized.備註
The behavior of
__iter__()is unlike that of dictionaries, whichiterate over keys.
- values()¶
The same as
itervalues(), except that alistis returnedrather than aniterator
- iteritems()¶
Return aniterator over (key,message) pairs, wherekey isa key andmessage is a message representation. The messages arerepresented as instances of the appropriate format-specific
Messagesubclass unless a custom message factory was specifiedwhen theMailboxinstance was initialized.
- items()¶
The same as
iteritems(), except that alistof pairs isreturned rather than aniterator of pairs.
- get(key,default=None)¶
- __getitem__(key)¶
Return a representation of the message corresponding tokey. If no suchmessage exists,default is returned if the method was called as
get()and aKeyErrorexception is raised if the method wascalled as__getitem__(). The message is represented as an instanceof the appropriate format-specificMessagesubclass unless acustom message factory was specified when theMailboxinstancewas initialized.
- get_message(key)¶
Return a representation of the message corresponding tokey as aninstance of the appropriate format-specific
Messagesubclass, orraise aKeyErrorexception if no such message exists.
- get_bytes(key)¶
Return a byte representation of the message corresponding tokey, orraise a
KeyErrorexception if no such message exists.在 3.2 版被加入.
- get_string(key)¶
Return a string representation of the message corresponding tokey, orraise a
KeyErrorexception if no such message exists. Themessage is processed throughemail.message.Messagetoconvert it to a 7bit clean representation.
- get_file(key)¶
Return afile-like representation of themessage corresponding tokey,or raise a
KeyErrorexception 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 abinary file; previously it wasincorrectly returned in text mode. Also, thefile-like objectnow supports thecontext manager protocol: you can use a
withstatement to automatically close it.備註
Unlike other representations of messages,file-like representations are notnecessarily independent of the
Mailboxinstance thatcreated them or of the underlying mailbox. More specific documentationis provided by each subclass.
- __contains__(key)¶
Return
Trueifkey corresponds to a message,Falseotherwise.
- __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 tokey and deletethe message. If no such message exists, returndefault. The message isrepresented as an instance of the appropriate format-specific
Messagesubclass unless a custom message factory was specifiedwhen theMailboxinstance was initialized.
- popitem()¶
Return an arbitrary (key,message) pair, wherekey is a key andmessage is a message representation, and delete the correspondingmessage. If the mailbox is empty, raise a
KeyErrorexception. Themessage is represented as an instance of the appropriate format-specificMessagesubclass unless a custom message factory was specifiedwhen theMailboxinstance was initialized.
- update(arg)¶
Parameterarg should be akey-to-message mapping or an iterable of(key,message) pairs. Updates the mailbox so that, for each givenkey andmessage, the message corresponding tokey is set tomessage as if by using
__setitem__(). As with__setitem__(),eachkey must already correspond to a message in the mailbox or else aKeyErrorexception will be raised, so in general it is incorrectforarg to be aMailboxinstance.備註
Unlike with dictionaries, keyword arguments are not supported.
- flush()¶
Write any pending changes to the filesystem. For some
Mailboxsubclasses, changes are always written immediately andflush()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
ExternalClashErroris raised if the lockis not available. The particular locking mechanisms used depend upon themailbox format. You shouldalways 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
Mailboxsubclasses, this method does nothing.
Mailbox 物件¶
- classmailbox.Maildir(dirname,factory=None,create=True)¶
A subclass of
Mailboxfor 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.Iffactory isNone,MaildirMessageis used as the default messagerepresentation. Ifcreate isTrue, the mailbox is created if it does notexist.Ifcreate is
Trueand thedirname path exists, it will be treated asan existing maildir without attempting to verify its directory layout.It is for historical reasons thatdirname is named as such rather thanpath.
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, andcur. Messages are created momentarily in thetmpsubdirectory and then moved to thenewsubdirectory tofinalize delivery. A mail user agent may subsequently move the message to thecursubdirectory 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 byMaildirwithout 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".- colon¶
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:importmailboxmailbox.Maildir.colon='!'
The
colonattribute may also be set on a per-instance basis.
在 3.13 版的變更:
Maildirnow ignores files with a leading dot.Maildirinstances have all of the methods ofMailboxinaddition to the following:- list_folders()¶
Return a list of the names of all folders.
- get_folder(folder)¶
Return a
Maildirinstance representing the folder whose name isfolder. ANoSuchMailboxErrorexception is raised if the folderdoes not exist.
- add_folder(folder)¶
Create a folder whose name isfolder and return a
Maildirinstance representing it.
- remove_folder(folder)¶
Delete the folder whose name isfolder. If the folder contains anymessages, a
NotEmptyErrorexception 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.
- get_flags(key)¶
Return as a string the flags that are set on the messagecorresponding tokey.This is the same as
get_message(key).get_flags()but muchfaster, because it does not open the message file.Use this method when iterating over the keys to determine whichmessages are interesting to get.If you do have a
MaildirMessageobject, useitsget_flags()method instead, becausechanges made by the message'sset_flags(),add_flag()andremove_flag()methods are not reflected here until the mailbox's__setitem__()method is called.在 3.13 版被加入.
- set_flags(key,flags)¶
On the message corresponding tokey, set the flags specifiedbyflags and unset all others.Calling
some_mailbox.set_flags(key,flags)is similar toone_message=some_mailbox.get_message(key)one_message.set_flags(flags)some_mailbox[key]=one_message
but faster, because it does not open the message file.
If you do have a
MaildirMessageobject, useitsset_flags()method instead, becausechanges made with this mailbox method will not be visible to themessage object's method,get_flags().在 3.13 版被加入.
- add_flag(key,flag)¶
On the message corresponding tokey, set the flags specifiedbyflag without changing other flags. To add more than oneflag at a time,flag may be a string of more than one character.
Considerations for using this method versus the message object's
add_flag()method are similar tothose forset_flags(); see the discussion there.在 3.13 版被加入.
- remove_flag(key,flag)¶
On the message corresponding tokey, unset the flags specifiedbyflag without changing other flags. To remove more than oneflag at a time,flag may be a string of more than one character.
Considerations for using this method versus the message object's
remove_flag()method are similar tothose forset_flags(); see the discussion there.在 3.13 版被加入.
- get_info(key)¶
Return a string containing the info for the messagecorresponding tokey.This is the same as
get_message(key).get_info()but muchfaster, because it does not open the message file.Use this method when iterating over the keys to determine whichmessages are interesting to get.If you do have a
MaildirMessageobject, useitsget_info()method instead, becausechanges made by the message'sset_info()methodare not reflected here until the mailbox's__setitem__()methodis called.在 3.13 版被加入.
- set_info(key,info)¶
Set the info of the message corresponding tokey toinfo.Calling
some_mailbox.set_info(key,flags)is similar toone_message=some_mailbox.get_message(key)one_message.set_info(info)some_mailbox[key]=one_message
but faster, because it does not open the message file.
If you do have a
MaildirMessageobject, useitsset_info()method instead, becausechanges made with this mailbox method will not be visible to themessage object's method,get_info().在 3.13 版被加入.
Some
Mailboxmethods implemented byMaildirdeserve 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.
- close()¶
Maildirinstances do not keep any open files and the underlyingmailboxes do not support locking, so this method does nothing.
- get_file(key)¶
Depending upon the host platform, it may not be possible to modify orremove the underlying message while the returned file remains open.
也參考
- maildir man page from Courier
A specification of the format. Describes a common extension forsupporting folders.
- Using maildir format
Notes on Maildir by its inventor. Includes an updated name-creation scheme anddetails on "info" semantics.
mbox 物件¶
- classmailbox.mbox(path,factory=None,create=True)¶
A subclass of
Mailboxfor mailboxes in mbox format. Parameterfactoryis a callable object that accepts a file-like message representation (whichbehaves as if opened in binary mode) and returns a custom representation. Iffactory isNone,mboxMessageis used as the default messagerepresentation. Ifcreate isTrue, 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,
mboximplements theoriginal format, which is sometimes referred to asmboxo. This means thattheContent-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
Mailboxmethods implemented bymboxdeserve specialremarks:- get_bytes(key,from_=False)¶
Note: This method has an extra parameter (from_) compared with other classes.The first line of an mbox file entry is the Unix "From " line.Iffrom_ is False, the first line of the file is dropped.
- get_file(key,from_=False)¶
Using the file after calling
flush()orclose()on themboxinstance may yieldunpredictable results or raise an exception.Note: This method has an extra parameter (from_) compared with other classes.The first line of an mbox file entry is the Unix "From " line.Iffrom_ is False, the first line of the file is dropped.
- get_string(key,from_=False)¶
Note: This method has an extra parameter (from_) compared with other classes.The first line of an mbox file entry is the Unix "From " line.Iffrom_ is False, the first line of the file is dropped.
也參考
- mbox man page from tin
A specification of the format, with details on locking.
- Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad
An argument for using the original mbox format rather than a variation.
- "mbox" is a family of several mutually incompatible mailbox formats
A history of mbox variations.
MH 物件¶
- classmailbox.MH(path,factory=None,create=True)¶
A subclass of
Mailboxfor mailboxes in MH format. Parameterfactoryis a callable object that accepts a file-like message representation (whichbehaves as if opened in binary mode) and returns a custom representation. Iffactory isNone,MHMessageis used as the default messagerepresentation. Ifcreate isTrue, 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 (calledfolders) inaddition to messages. Folders may be nested indefinitely. MH mailboxes alsosupportsequences, which are named lists used to logically groupmessages without moving them to sub-folders. Sequences are defined in a filecalled
.mh_sequencesin each folder.The
MHclass manipulates MH mailboxes, but it does not attempt toemulate all ofmh's behaviors. In particular, it does not modifyand is not affected by thecontextor.mh_profilefiles thatare used bymh to store its state and configuration.MHinstances have all of the methods ofMailboxin additionto the following:在 3.13 版的變更:Supported folders that don't contain a
.mh_sequencesfile.- list_folders()¶
Return a list of the names of all folders.
- get_folder(folder)¶
Return an
MHinstance representing the folder whose name isfolder. ANoSuchMailboxErrorexception is raised if the folderdoes not exist.
- add_folder(folder)¶
Create a folder whose name isfolder and return an
MHinstancerepresenting it.
- remove_folder(folder)¶
Delete the folder whose name isfolder. If the folder contains anymessages, a
NotEmptyErrorexception 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.
- set_sequences(sequences)¶
Re-define the sequences that exist in the mailbox based uponsequences,a dictionary of names mapped to key lists, like returned by
get_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
Mailboxmethods implemented byMHdeserve 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, the
flock()andlockf()system calls. For MH mailboxes, lockingthe mailbox means locking the.mh_sequencesfile and, only for theduration of any operations that affect them, locking individual messagefiles.
- get_file(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.
也參考
- nmh - Message Handling System
Home page ofnmh, an updated version of the originalmh.
- MH & nmh: Email for Users & Programmers
A GPL-licensed book onmh andnmh, with some informationon the mailbox format.
Babyl 物件¶
- classmailbox.Babyl(path,factory=None,create=True)¶
A subclass of
Mailboxfor 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.Iffactory isNone,BabylMessageis used as the default messagerepresentation. Ifcreate isTrue, 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.
Babylinstances have all of the methods ofMailboxinaddition 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
Mailboxmethods implemented byBabyldeserve specialremarks:- get_file(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.BytesIOinstance,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.
也參考
- Format of Version 5 Babyl Files
A specification of the Babyl format.
- Reading Mail with Rmail
The Rmail manual, with some information on Babyl semantics.
MMDF 物件¶
- classmailbox.MMDF(path,factory=None,create=True)¶
A subclass of
Mailboxfor mailboxes in MMDF format. Parameterfactoryis a callable object that accepts a file-like message representation (whichbehaves as if opened in binary mode) and returns a custom representation. Iffactory isNone,MMDFMessageis used as the default messagerepresentation. Ifcreate isTrue, 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
Mailboxmethods implemented byMMDFdeserve specialremarks:- get_bytes(key,from_=False)¶
Note: This method has an extra parameter (from_) compared with other classes.The first line of an mbox file entry is the Unix "From " line.Iffrom_ is False, the first line of the file is dropped.
- get_file(key,from_=False)¶
Using the file after calling
flush()orclose()on theMMDFinstance may yieldunpredictable results or raise an exception.Note: This method has an extra parameter (from_) compared with other classes.The first line of an mbox file entry is the Unix "From " line.Iffrom_ is False, the first line of the file is dropped.
也參考
- 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 物件¶
- classmailbox.Message(message=None)¶
A subclass of the
email.messagemodule'sMessage. Subclasses ofmailbox.Messageaddmailbox-format-specific state and behavior.Ifmessage is omitted, the new instance is created in a default, empty state.Ifmessage is an
email.message.Messageinstance, its contents arecopied; furthermore, any format-specific information is converted insofar aspossible ifmessage is aMessageinstance. Ifmessage is a string,a byte string,or a file, it should contain anRFC 5322-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
Messageinstances be used to representmessages retrieved usingMailboxinstances. In some situations, thetime and memory required to generateMessagerepresentations mightnot be acceptable. For such situations,Mailboxinstances alsooffer string and file-like representations, and a custom message factory maybe specified when aMailboxinstance is initialized.
MaildirMessage 物件¶
- classmailbox.MaildirMessage(message=None)¶
A message with Maildir-specific behaviors. Parametermessage has the samemeaning as with the
Messageconstructor.Typically, a mail user agent application moves all of the messages in the
newsubdirectory to thecursubdirectory 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 incurhas 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
草稿
編輯中
F
已標記
標記為重要
P
Passed
Forwarded, resent, or bounced
R
已回覆
Replied to
S
已查看
Read
T
Trashed
Marked for subsequent deletion
MaildirMessage實例提供以下方法:- get_subdir()¶
Return either "new" (if the message should be stored in the
newsubdirectory) or "cur" (if the message should be stored in thecursubdirectory).備註
A message is typically moved from
newtocurafter itsmailbox has been accessed, whether or not the message has beenread. A messagemsghas been read if"S"inmsg.get_flags()isTrue.
- set_subdir(subdir)¶
Set the subdirectory the message should be stored in. Parametersubdirmust 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.
- set_flags(flags)¶
Set the flags specified byflags and unset all others.
- add_flag(flag)¶
Set the flag(s) specified byflag 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.
- remove_flag(flag)¶
Unset the flag(s) specified byflag 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.
- set_date(date)¶
Set the delivery date of the message todate, 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).
- set_info(info)¶
Set "info" toinfo, which should be a string.
When aMaildirMessage instance is created based upon anmboxMessage orMMDFMessage instance, theStatusandX-Status headers are omitted and the following conversionstake place:
Resulting state | |
|---|---|
"cur" 子目錄 | O 旗標 |
F 旗標 | F 旗標 |
R 旗標 | A 旗標 |
S 旗標 | R 旗標 |
T 旗標 | D 旗標 |
When aMaildirMessage instance is created based upon anMHMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
"cur" 子目錄 | "unseen" 序列 |
"cur" 子目錄和 S 旗標 | 沒有 "unseen" 序列 |
F 旗標 | "flagged" 序列 |
R 旗標 | "replied" 序列 |
When aMaildirMessage instance is created based upon aBabylMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
"cur" 子目錄 | "unseen" 標籤 |
"cur" 子目錄和 S 旗標 | 沒有 "unseen" 標籤 |
P 旗標 | "forwarded" 或 "resent" 標籤 |
R 旗標 | "answered" 標籤 |
T 旗標 | "deleted" 標籤 |
mboxMessage 物件¶
- classmailbox.mboxMessage(message=None)¶
A message with mbox-specific behaviors. Parametermessage has the same meaningas with the
Messageconstructor.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 andX-Status headers.
Conventional flags for mbox messages are as follows:
旗標
含義
解釋
R
Read
Read
O
Old
Previously detected by MUA
D
Deleted
Marked for subsequent deletion
F
已標記
標記為重要
A
Answered
Replied to
The "R" and "O" flags are stored in theStatus header, and the"D", "F", and "A" flags are stored in theX-Status header. Theflags and headers typically appear in the order mentioned.
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.
- set_from(from_,time_=None)¶
Set the "From " line tofrom_, which should be specified without aleading "From " or trailing newline. For convenience,time_ may bespecified and will be formatted appropriately and appended tofrom_. Iftime_ is specified, it should be a
time.struct_timeinstance, atuple suitable for passing totime.strftime(), orTrue(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'.
- set_flags(flags)¶
Set the flags specified byflags and unset all others. Parameterflagsshould be the concatenation in any order of zero or more occurrences ofeach of
'R','O','D','F', and'A'.
- add_flag(flag)¶
Set the flag(s) specified byflag without changing other flags. To addmore than one flag at a time,flag may be a string of more than onecharacter.
- remove_flag(flag)¶
Unset the flag(s) specified byflag without changing other flags. Toremove more than one flag at a time,flag maybe a string of more thanone character.
When anmboxMessage instance is created based upon aMaildirMessage instance, a "From " line is generated based upon theMaildirMessage instance's delivery date, and the following conversionstake place:
Resulting state | |
|---|---|
R 旗標 | S 旗標 |
O 旗標 | "cur" 子目錄 |
D 旗標 | T 旗標 |
F 旗標 | F 旗標 |
A 旗標 | R 旗標 |
When anmboxMessage instance is created based upon anMHMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
R 旗標和 O 旗標 | 沒有 "unseen" 序列 |
O 旗標 | "unseen" 序列 |
F 旗標 | "flagged" 序列 |
A 旗標 | "replied" 序列 |
When anmboxMessage instance is created based upon aBabylMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
R 旗標和 O 旗標 | 沒有 "unseen" 標籤 |
O 旗標 | "unseen" 標籤 |
D 旗標 | "deleted" 標籤 |
A 旗標 | "answered" 標籤 |
When amboxMessage instance is created based upon anMMDFMessageinstance, the "From " line is copied and all flags directly correspond:
Resulting state |
|
|---|---|
R 旗標 | R 旗標 |
O 旗標 | O 旗標 |
D 旗標 | D 旗標 |
F 旗標 | F 旗標 |
A 旗標 | A 旗標 |
MHMessage 物件¶
- classmailbox.MHMessage(message=None)¶
A message with MH-specific behaviors. Parametermessage has the same meaningas with the
Messageconstructor.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 standardmh andnmh) use sequences in much the same way flags are used with otherformats, as follows:
Sequence
解釋
unseen
Not read, but previously detected by MUA
replied
Replied to
flagged
標記為重要
MHMessage實例提供以下方法:- get_sequences()¶
Return a list of the names of sequences that include this message.
- set_sequences(sequences)¶
Set the list of sequences that include this message.
- add_sequence(sequence)¶
Addsequence to the list of sequences that include this message.
- remove_sequence(sequence)¶
Removesequence from the list of sequences that include this message.
When anMHMessage instance is created based upon aMaildirMessage instance, the following conversions take place:
Resulting state | |
|---|---|
"unseen" 序列 | 無 S 旗標 |
"replied" 序列 | R 旗標 |
"flagged" 序列 | F 旗標 |
When anMHMessage instance is created based upon anmboxMessage orMMDFMessage instance, theStatusandX-Status headers are omitted and the following conversionstake place:
Resulting state | |
|---|---|
"unseen" 序列 | 無 R 旗標 |
"replied" 序列 | A 旗標 |
"flagged" 序列 | F 旗標 |
When anMHMessage instance is created based upon aBabylMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
"unseen" 序列 | "unseen" 標籤 |
"replied" 序列 | "answered" 標籤 |
BabylMessage 物件¶
- classmailbox.BabylMessage(message=None)¶
A message with Babyl-specific behaviors. Parametermessage has the samemeaning as with the
Messageconstructor.Certain message labels, calledattributes, are defined by conventionto have special meanings. The attributes are as follows:
Label
解釋
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
BabylMessageclass, though, uses the original headers because they are morecomplete. Visible headers may be accessed explicitly if desired.BabylMessage實例提供以下方法:- get_labels()¶
Return a list of labels on the message.
- set_labels(labels)¶
Set the list of labels on the message tolabels.
- add_label(label)¶
Addlabel to the list of labels on the message.
- remove_label(label)¶
Removelabel from the list of labels on the message.
- get_visible()¶
Return a
Messageinstance whose headers are the message'svisible headers and whose body is empty.
- set_visible(visible)¶
Set the message's visible headers to be the same as the headers inmessage. Parametervisible should be a
Messageinstance, anemail.message.Messageinstance, a string, or a file-like object(which should be open in text mode).
- update_visible()¶
When a
BabylMessageinstance'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 ofDate,From,Reply-To,To,CC, andSubject that arepresent in the original headers but not the visible headers are added tothe visible headers.
When aBabylMessage instance is created based upon aMaildirMessage instance, the following conversions take place:
Resulting state | |
|---|---|
"unseen" 標籤 | 無 S 旗標 |
"deleted" 標籤 | T 旗標 |
"answered" 標籤 | R 旗標 |
"forwarded" 標籤 | P 旗標 |
When aBabylMessage instance is created based upon anmboxMessage orMMDFMessage instance, theStatusandX-Status headers are omitted and the following conversionstake place:
Resulting state | |
|---|---|
"unseen" 標籤 | 無 R 旗標 |
"deleted" 標籤 | D 旗標 |
"answered" 標籤 | A 旗標 |
When aBabylMessage instance is created based upon anMHMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
"unseen" 標籤 | "unseen" 序列 |
"answered" 標籤 | "replied" 序列 |
MMDFMessage 物件¶
- classmailbox.MMDFMessage(message=None)¶
A message with MMDF-specific behaviors. Parametermessage has the same meaningas with the
Messageconstructor.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 inStatus andX-Status headers.
Conventional flags for MMDF messages are identical to those of mbox messageand are as follows:
旗標
含義
解釋
R
Read
Read
O
Old
Previously detected by MUA
D
Deleted
Marked for subsequent deletion
F
已標記
標記為重要
A
Answered
Replied to
The "R" and "O" flags are stored in theStatus header, and the"D", "F", and "A" flags are stored in theX-Status header. Theflags and headers typically appear in the order mentioned.
MMDFMessageinstances offer the following methods, which areidentical to those offered bymboxMessage:- 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.
- set_from(from_,time_=None)¶
Set the "From " line tofrom_, which should be specified without aleading "From " or trailing newline. For convenience,time_ may bespecified and will be formatted appropriately and appended tofrom_. Iftime_ is specified, it should be a
time.struct_timeinstance, atuple suitable for passing totime.strftime(), orTrue(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'.
- set_flags(flags)¶
Set the flags specified byflags and unset all others. Parameterflagsshould be the concatenation in any order of zero or more occurrences ofeach of
'R','O','D','F', and'A'.
- add_flag(flag)¶
Set the flag(s) specified byflag without changing other flags. To addmore than one flag at a time,flag may be a string of more than onecharacter.
- remove_flag(flag)¶
Unset the flag(s) specified byflag without changing other flags. Toremove more than one flag at a time,flag maybe a string of more thanone character.
When anMMDFMessage instance is created based upon aMaildirMessage instance, a "From " line is generated based upon theMaildirMessage instance's delivery date, and the following conversionstake place:
Resulting state | |
|---|---|
R 旗標 | S 旗標 |
O 旗標 | "cur" 子目錄 |
D 旗標 | T 旗標 |
F 旗標 | F 旗標 |
A 旗標 | R 旗標 |
When anMMDFMessage instance is created based upon anMHMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
R 旗標和 O 旗標 | 沒有 "unseen" 序列 |
O 旗標 | "unseen" 序列 |
F 旗標 | "flagged" 序列 |
A 旗標 | "replied" 序列 |
When anMMDFMessage instance is created based upon aBabylMessage instance, the following conversions take place:
Resulting state |
|
|---|---|
R 旗標和 O 旗標 | 沒有 "unseen" 標籤 |
O 旗標 | "unseen" 標籤 |
D 旗標 | "deleted" 標籤 |
A 旗標 | "answered" 標籤 |
When anMMDFMessage instance is created based upon anmboxMessage instance, the "From " line is copied and all flags directlycorrespond:
Resulting state |
|
|---|---|
R 旗標 | R 旗標 |
O 旗標 | O 旗標 |
D 旗標 | D 旗標 |
F 旗標 | F 旗標 |
A 旗標 | A 旗標 |
例外¶
The following exception classes are defined in themailbox module:
- exceptionmailbox.Error¶
The based class for all other module-specific exceptions.
- exceptionmailbox.NoSuchMailboxError¶
Raised when a mailbox is expected but is not found, such as when instantiating a
Mailboxsubclass with a path that does not exist (and with thecreateparameter set toFalse), or when opening a folder that does not exist.
- exceptionmailbox.NotEmptyError¶
Raised when a mailbox is not empty but is expected to be, such as when deletinga folder that contains messages.
- exceptionmailbox.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.
範例¶
A simple example of printing the subjects of all messages in a mailbox that seeminteresting:
importmailboxformessageinmailbox.mbox('~/mbox'):subject=message['subject']# 可能為 None.ifsubjectand'python'insubject.lower():print(subject)
To copy all mail from a Babyl mailbox to an MH mailbox, converting all of theformat-specific information that can be converted:
importmailboxdestination=mailbox.MH('~/Mail')destination.lock()formessageinmailbox.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 otherprograms, mail loss due to interruption of the program, or premature terminationdue to malformed messages in the mailbox:
importmailboximportemail.errorslist_names=('python-list','python-dev','python-bugs')boxes={name:mailbox.mbox('~/email/%s'%name)fornameinlist_names}inbox=mailbox.Maildir('~/Maildir',factory=None)forkeyininbox.iterkeys():try:message=inbox[key]exceptemail.errors.MessageParseError:continue# The message is malformed. Just leave it.fornameinlist_names:list_id=message['list-id']iflist_idandnameinlist_id:# Get mailbox to usebox=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 messageinbox.lock()inbox.discard(key)inbox.flush()inbox.unlock()break# Found destination, so stop looking.forboxinboxes.itervalues():box.close()