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.

TheMailbox 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.

TheMailbox interface is dictionary-like, with small keyscorresponding to messages. Keys are issued by theMailbox instancewith 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 aMailbox instance using the set-likemethodadd() and removed using adel statement or the set-likemethodsremove() anddiscard().

Mailbox interface semantics differ from dictionary semantics in somenoteworthy ways. Each time a message is requested, a new representation(typically aMessage 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 bytheMailbox instance.

The defaultMailboxiterator 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 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 isMaildir; try to avoid using single-file formats such asmbox forconcurrent 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.

Mailbox instances have the following methods:

add(message)

Addmessage to the mailbox and return the key that has been assigned toit.

Parametermessage may be aMessage instance, anemail.message.Message instance, a string, a byte string, or afile-like object (which should be open in binary mode). Ifmessage isan instance of theappropriate format-specificMessage subclass (e.g., if it's anmboxMessage instance and this is anmbox 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 tokey from the mailbox.

If no such message exists, aKeyError exception 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 aKeyError exception if no message already corresponds tokey.

As withadd(), parametermessage may be aMessageinstance, anemail.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-specificMessage subclass(e.g., if it's anmboxMessage instance and this is anmbox instance), its format-specific information isused. Otherwise, the format-specific information of the message thatcurrently corresponds tokey is left unchanged.

iterkeys()

Return aniterator over all keys

keys()

The same asiterkeys(), except that alist is returnedrather than aniterator

itervalues()
__iter__()

Return aniterator over representations of all messages.The messages are representedas instances of the appropriate format-specificMessage subclassunless 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 asitervalues(), except that alist is 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-specificMessage subclass unless a custom message factory was specifiedwhen theMailbox instance was initialized.

items()

The same asiteritems(), except that alist of 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 asget() and aKeyError exception is raised if the method wascalled as__getitem__(). The message is represented as an instanceof the appropriate format-specificMessage subclass unless acustom message factory was specified when theMailbox instancewas initialized.

get_message(key)

Return a representation of the message corresponding tokey as aninstance of the appropriate format-specificMessage subclass, orraise aKeyError exception if no such message exists.

get_bytes(key)

Return a byte representation of the message corresponding tokey, orraise aKeyError exception if no such message exists.

在 3.2 版被加入.

get_string(key)

Return a string representation of the message corresponding tokey, orraise aKeyError exception if no such message exists. Themessage is processed throughemail.message.Message toconvert it to a 7bit clean representation.

get_file(key)

Return afile-like representation of themessage corresponding tokey,or raise aKeyError 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 abinary file; previously it wasincorrectly returned in text mode. Also, thefile-like objectnow supports thecontext manager protocol: you can use awith statement to automatically close it.

備註

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

__contains__(key)

ReturnTrue ifkey 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 tokey and deletethe message. If no such message exists, returndefault. The message isrepresented as an instance of the appropriate format-specificMessage subclass unless a custom message factory was specifiedwhen theMailbox instance 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 aKeyError exception. Themessage is represented as an instance of the appropriate format-specificMessage subclass unless a custom message factory was specifiedwhen theMailbox instance 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 aKeyError exception will be raised, so in general it is incorrectforarg to be aMailbox instance.

備註

Unlike with dictionaries, keyword arguments are not supported.

flush()

Write any pending changes to the filesystem. For someMailboxsubclasses, 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. AnExternalClashError is 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. ForsomeMailbox subclasses, this method does nothing.

Mailbox 物件

classmailbox.Maildir(dirname,factory=None,create=True)

A subclass ofMailbox 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.Iffactory isNone,MaildirMessage is used as the default messagerepresentation. Ifcreate isTrue, the mailbox is created if it does notexist.

Ifcreate isTrue and 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 thetmp subdirectory and then moved to thenew 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".

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='!'

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

在 3.13 版的變更:Maildir now ignores files with a leading dot.

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

list_folders()

Return a list of the names of all folders.

get_folder(folder)

Return aMaildir instance representing the folder whose name isfolder. ANoSuchMailboxError exception is raised if the folderdoes not exist.

add_folder(folder)

Create a folder whose name isfolder and return aMaildirinstance representing it.

remove_folder(folder)

Delete the folder whose name isfolder. If the folder contains anymessages, aNotEmptyError 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.

get_flags(key)

Return as a string the flags that are set on the messagecorresponding tokey.This is the same asget_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 aMaildirMessage object, 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.Callingsome_mailbox.set_flags(key,flags) is similar to

one_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 aMaildirMessage object, 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'sadd_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'sremove_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 asget_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 aMaildirMessage object, 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.Callingsome_mailbox.set_info(key,flags) is similar to

one_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 aMaildirMessage object, useitsset_info() method instead, becausechanges made with this mailbox method will not be visible to themessage object's method,get_info().

在 3.13 版被加入.

SomeMailbox methods implemented byMaildir 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.

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 ofMailbox for 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,mboxMessage is 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,mbox implements 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.

SomeMailbox methods implemented bymbox deserve 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 callingflush() orclose() on thembox instance 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.

lock()
unlock()

Three locking mechanisms are used---dot locking and, if available, theflock() andlockf() system calls.

也參考

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 ofMailbox for 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,MHMessage is 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_sequences in each folder.

TheMH class manipulates MH mailboxes, but it does not attempt toemulate all ofmh's behaviors. In particular, it does not modifyand is not affected by thecontext or.mh_profile files thatare used bymh to store its state and configuration.

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

在 3.13 版的變更:Supported folders that don't contain a.mh_sequences file.

list_folders()

Return a list of the names of all folders.

get_folder(folder)

Return anMH instance representing the folder whose name isfolder. ANoSuchMailboxError exception is raised if the folderdoes not exist.

add_folder(folder)

Create a folder whose name isfolder and return anMH instancerepresenting it.

remove_folder(folder)

Delete the folder whose name isfolder. If the folder contains anymessages, aNotEmptyError 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.

set_sequences(sequences)

Re-define the sequences that exist in the mailbox based uponsequences,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.

SomeMailbox methods implemented byMH 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() andlockf() 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.

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.

close()

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

也參考

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 ofMailbox 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.Iffactory isNone,BabylMessage is 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.

Babyl instances have all of the methods ofMailbox 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.

SomeMailbox methods implemented byBabyl deserve 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 anio.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() andlockf() system calls.

也參考

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 ofMailbox for 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,MMDFMessage is 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.

SomeMailbox methods implemented byMMDF deserve 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 callingflush() orclose() on theMMDF instance 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.

lock()
unlock()

Three locking mechanisms are used---dot locking and, if available, theflock() andlockf() 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 物件

classmailbox.Message(message=None)

A subclass of theemail.message module'sMessage. Subclasses ofmailbox.Message addmailbox-format-specific state and behavior.

Ifmessage is omitted, the new instance is created in a default, empty state.Ifmessage is anemail.message.Message instance, its contents arecopied; furthermore, any format-specific information is converted insofar aspossible ifmessage is aMessage instance. Ifmessage is a string,a byte string,or a file, it should contain anRFC 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 thatMessage instances be used to representmessages retrieved usingMailbox instances. In some situations, thetime and memory required to generateMessage representations mightnot be acceptable. For such situations,Mailbox instances alsooffer string and file-like representations, and a custom message factory maybe specified when aMailbox instance is initialized.

MaildirMessage 物件

classmailbox.MaildirMessage(message=None)

A message with Maildir-specific behaviors. Parametermessage has the samemeaning as with theMessage constructor.

Typically, a mail user agent application moves all of the messages in thenew subdirectory to thecur 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 incur 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:

Flag

含義

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:

get_subdir()

Return either "new" (if the message should be stored in thenewsubdirectory) or "cur" (if the message should be stored in thecursubdirectory).

備註

A message is typically moved fromnew tocur after itsmailbox has been accessed, whether or not the message has beenread. A messagemsg has 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

mboxMessage orMMDFMessagestate

"cur" subdirectory

O flag

F flag

F flag

R flag

A flag

S flag

R flag

T flag

D flag

When aMaildirMessage instance is created based upon anMHMessage 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 aMaildirMessage instance is created based upon aBabylMessage 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

mboxMessage 物件

classmailbox.mboxMessage(message=None)

A message with mbox-specific behaviors. Parametermessage has the same meaningas with theMessage 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 andX-Status headers.

Conventional flags for mbox messages are as follows:

Flag

含義

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 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 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.

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 atime.struct_time instance, 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

MaildirMessage state

R flag

S flag

O flag

"cur" subdirectory

D flag

T flag

F flag

F flag

A flag

R flag

When anmboxMessage instance is created based upon anMHMessage 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 anmboxMessage instance is created based upon aBabylMessage 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 amboxMessage instance is created based upon anMMDFMessageinstance, 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

MHMessage 物件

classmailbox.MHMessage(message=None)

A message with MH-specific behaviors. Parametermessage has the same meaningas with theMessage 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 standardmh andnmh) use sequences in much the same way flags are used with otherformats, 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:

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

MaildirMessage state

"unseen" sequence

no S flag

"replied" sequence

R flag

"flagged" sequence

F flag

When anMHMessage instance is created based upon anmboxMessage orMMDFMessage instance, theStatusandX-Status headers are omitted and the following conversionstake place:

Resulting state

mboxMessage orMMDFMessagestate

"unseen" sequence

no R flag

"replied" sequence

A flag

"flagged" sequence

F flag

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

Resulting state

BabylMessage state

"unseen" sequence

"unseen" label

"replied" sequence

"answered" label

BabylMessage 物件

classmailbox.BabylMessage(message=None)

A message with Babyl-specific behaviors. Parametermessage has the samemeaning as with theMessage constructor.

Certain message labels, calledattributes, are defined by conventionto 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. TheBabylMessageclass, 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()

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 aMessage instance 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 aMessage instance, anemail.message.Message instance, a string, or a file-like object(which should be open in text mode).

update_visible()

When aBabylMessage 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 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

MaildirMessage state

"unseen" label

no S flag

"deleted" label

T flag

"answered" label

R flag

"forwarded" label

P flag

When aBabylMessage instance is created based upon anmboxMessage orMMDFMessage instance, theStatusandX-Status headers are omitted and the following conversionstake place:

Resulting state

mboxMessage orMMDFMessagestate

"unseen" label

no R flag

"deleted" label

D flag

"answered" label

A flag

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

Resulting state

MHMessage state

"unseen" label

"unseen" sequence

"answered" label

"replied" sequence

MMDFMessage 物件

classmailbox.MMDFMessage(message=None)

A message with MMDF-specific behaviors. Parametermessage has the same meaningas with theMessage 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 inStatus andX-Status headers.

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

Flag

含義

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 theStatus header, and the"D", "F", and "A" flags are stored in theX-Status header. Theflags and headers typically appear in the order mentioned.

MMDFMessage instances 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 atime.struct_time instance, 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

MaildirMessage state

R flag

S flag

O flag

"cur" subdirectory

D flag

T flag

F flag

F flag

A flag

R flag

When anMMDFMessage instance is created based upon anMHMessage 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 anMMDFMessage instance is created based upon aBabylMessage 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 anMMDFMessage instance is created based upon anmboxMessage instance, the "From " line is copied and all flags directlycorrespond:

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 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 aMailbox subclass 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.

exceptionmailbox.FormatError

Raised when the data in a file cannot be parsed, such as when anMHinstance attempts to read a corrupted.mh_sequences file.

範例

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()