2 :mod:`mailbox` --- Manipulate mailboxes in various formats
3 ==========================================================
6 :synopsis: Manipulate mailboxes in various formats
7 .. moduleauthor:: Gregory K. Johnson <gkj@gregorykjohnson.com>
8 .. sectionauthor:: Gregory K. Johnson <gkj@gregorykjohnson.com>
11 This module defines two classes, :class:`Mailbox` and :class:`Message`, for
12 accessing and manipulating on-disk mailboxes and the messages they contain.
13 :class:`Mailbox` offers a dictionary-like mapping from keys to messages.
14 :class:`Message` extends the :mod:`email.Message` module's :class:`Message`
15 class with format-specific state and behavior. Supported mailbox formats are
16 Maildir, mbox, MH, Babyl, and MMDF.
22 Represent and manipulate messages.
27 :class:`Mailbox` objects
28 ------------------------
33 A mailbox, which may be inspected and modified.
35 The :class:`Mailbox` class defines an interface and is not intended to be
36 instantiated. Instead, format-specific subclasses should inherit from
37 :class:`Mailbox` and your code should instantiate a particular subclass.
39 The :class:`Mailbox` interface is dictionary-like, with small keys corresponding
40 to messages. Keys are issued by the :class:`Mailbox` instance with which they
41 will be used and are only meaningful to that :class:`Mailbox` instance. A key
42 continues to identify a message even if the corresponding message is modified,
43 such as by replacing it with another message.
45 Messages may be added to a :class:`Mailbox` instance using the set-like method
46 :meth:`add` and removed using a ``del`` statement or the set-like methods
47 :meth:`remove` and :meth:`discard`.
49 :class:`Mailbox` interface semantics differ from dictionary semantics in some
50 noteworthy ways. Each time a message is requested, a new representation
51 (typically a :class:`Message` instance) is generated based upon the current
52 state of the mailbox. Similarly, when a message is added to a :class:`Mailbox`
53 instance, the provided message representation's contents are copied. In neither
54 case is a reference to the message representation kept by the :class:`Mailbox`
57 The default :class:`Mailbox` iterator iterates over message representations, not
58 keys as the default dictionary iterator does. Moreover, modification of a
59 mailbox during iteration is safe and well-defined. Messages added to the mailbox
60 after an iterator is created will not be seen by the iterator. Messages removed
61 from the mailbox before the iterator yields them will be silently skipped,
62 though using a key from an iterator may result in a :exc:`KeyError` exception if
63 the corresponding message is subsequently removed.
67 Be very cautious when modifying mailboxes that might be simultaneously changed
68 by some other process. The safest mailbox format to use for such tasks is
69 Maildir; try to avoid using single-file formats such as mbox for concurrent
70 writing. If you're modifying a mailbox, you *must* lock it by calling the
71 :meth:`lock` and :meth:`unlock` methods *before* reading any messages in the
72 file or making any changes by adding or deleting a message. Failing to lock the
73 mailbox runs the risk of losing messages or corrupting the entire mailbox.
75 :class:`Mailbox` instances have the following methods:
78 .. method:: Mailbox.add(message)
80 Add *message* to the mailbox and return the key that has been assigned to it.
82 Parameter *message* may be a :class:`Message` instance, an
83 :class:`email.Message.Message` instance, a string, or a file-like object (which
84 should be open in text mode). If *message* is an instance of the appropriate
85 format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage`
86 instance and this is an :class:`mbox` instance), its format-specific information
87 is used. Otherwise, reasonable defaults for format-specific information are
91 .. method:: Mailbox.remove(key)
92 Mailbox.__delitem__(key)
95 Delete the message corresponding to *key* from the mailbox.
97 If no such message exists, a :exc:`KeyError` exception is raised if the method
98 was called as :meth:`remove` or :meth:`__delitem__` but no exception is raised
99 if the method was called as :meth:`discard`. The behavior of :meth:`discard` may
100 be preferred if the underlying mailbox format supports concurrent modification
104 .. method:: Mailbox.__setitem__(key, message)
106 Replace the message corresponding to *key* with *message*. Raise a
107 :exc:`KeyError` exception if no message already corresponds to *key*.
109 As with :meth:`add`, parameter *message* may be a :class:`Message` instance, an
110 :class:`email.Message.Message` instance, a string, or a file-like object (which
111 should be open in text mode). If *message* is an instance of the appropriate
112 format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage`
113 instance and this is an :class:`mbox` instance), its format-specific information
114 is used. Otherwise, the format-specific information of the message that
115 currently corresponds to *key* is left unchanged.
118 .. method:: Mailbox.iterkeys()
121 Return an iterator over all keys if called as :meth:`iterkeys` or return a list
122 of keys if called as :meth:`keys`.
125 .. method:: Mailbox.itervalues()
129 Return an iterator over representations of all messages if called as
130 :meth:`itervalues` or :meth:`__iter__` or return a list of such representations
131 if called as :meth:`values`. The messages are represented as instances of the
132 appropriate format-specific :class:`Message` subclass unless a custom message
133 factory was specified when the :class:`Mailbox` instance was initialized.
137 The behavior of :meth:`__iter__` is unlike that of dictionaries, which iterate
141 .. method:: Mailbox.iteritems()
144 Return an iterator over (*key*, *message*) pairs, where *key* is a key and
145 *message* is a message representation, if called as :meth:`iteritems` or return
146 a list of such pairs if called as :meth:`items`. The messages are represented as
147 instances of the appropriate format-specific :class:`Message` subclass unless a
148 custom message factory was specified when the :class:`Mailbox` instance was
152 .. method:: Mailbox.get(key[, default=None])
153 Mailbox.__getitem__(key)
155 Return a representation of the message corresponding to *key*. If no such
156 message exists, *default* is returned if the method was called as :meth:`get`
157 and a :exc:`KeyError` exception is raised if the method was called as
158 :meth:`__getitem__`. The message is represented as an instance of the
159 appropriate format-specific :class:`Message` subclass unless a custom message
160 factory was specified when the :class:`Mailbox` instance was initialized.
163 .. method:: Mailbox.get_message(key)
165 Return a representation of the message corresponding to *key* as an instance of
166 the appropriate format-specific :class:`Message` subclass, or raise a
167 :exc:`KeyError` exception if no such message exists.
170 .. method:: Mailbox.get_string(key)
172 Return a string representation of the message corresponding to *key*, or raise a
173 :exc:`KeyError` exception if no such message exists.
176 .. method:: Mailbox.get_file(key)
178 Return a file-like representation of the message corresponding to *key*, or
179 raise a :exc:`KeyError` exception if no such message exists. The file-like
180 object behaves as if open in binary mode. This file should be closed once it is
185 Unlike other representations of messages, file-like representations are not
186 necessarily independent of the :class:`Mailbox` instance that created them or of
187 the underlying mailbox. More specific documentation is provided by each
191 .. method:: Mailbox.has_key(key)
192 Mailbox.__contains__(key)
194 Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
197 .. method:: Mailbox.__len__()
199 Return a count of messages in the mailbox.
202 .. method:: Mailbox.clear()
204 Delete all messages from the mailbox.
207 .. method:: Mailbox.pop(key[, default])
209 Return a representation of the message corresponding to *key* and delete the
210 message. If no such message exists, return *default* if it was supplied or else
211 raise a :exc:`KeyError` exception. The message is represented as an instance of
212 the appropriate format-specific :class:`Message` subclass unless a custom
213 message factory was specified when the :class:`Mailbox` instance was
217 .. method:: Mailbox.popitem()
219 Return an arbitrary (*key*, *message*) pair, where *key* is a key and *message*
220 is a message representation, and delete the corresponding message. If the
221 mailbox is empty, raise a :exc:`KeyError` exception. The message is represented
222 as an instance of the appropriate format-specific :class:`Message` subclass
223 unless a custom message factory was specified when the :class:`Mailbox` instance
227 .. method:: Mailbox.update(arg)
229 Parameter *arg* should be a *key*-to-*message* mapping or an iterable of (*key*,
230 *message*) pairs. Updates the mailbox so that, for each given *key* and
231 *message*, the message corresponding to *key* is set to *message* as if by using
232 :meth:`__setitem__`. As with :meth:`__setitem__`, each *key* must already
233 correspond to a message in the mailbox or else a :exc:`KeyError` exception will
234 be raised, so in general it is incorrect for *arg* to be a :class:`Mailbox`
239 Unlike with dictionaries, keyword arguments are not supported.
242 .. method:: Mailbox.flush()
244 Write any pending changes to the filesystem. For some :class:`Mailbox`
245 subclasses, changes are always written immediately and :meth:`flush` does
246 nothing, but you should still make a habit of calling this method.
249 .. method:: Mailbox.lock()
251 Acquire an exclusive advisory lock on the mailbox so that other processes know
252 not to modify it. An :exc:`ExternalClashError` is raised if the lock is not
253 available. The particular locking mechanisms used depend upon the mailbox
254 format. You should *always* lock the mailbox before making any modifications
258 .. method:: Mailbox.unlock()
260 Release the lock on the mailbox, if any.
263 .. method:: Mailbox.close()
265 Flush the mailbox, unlock it if necessary, and close any open files. For some
266 :class:`Mailbox` subclasses, this method does nothing.
275 .. class:: Maildir(dirname[, factory=rfc822.Message[, create=True]])
277 A subclass of :class:`Mailbox` for mailboxes in Maildir format. Parameter
278 *factory* is a callable object that accepts a file-like message representation
279 (which behaves as if opened in binary mode) and returns a custom representation.
280 If *factory* is ``None``, :class:`MaildirMessage` is used as the default message
281 representation. If *create* is ``True``, the mailbox is created if it does not
284 It is for historical reasons that *factory* defaults to :class:`rfc822.Message`
285 and that *dirname* is named as such rather than *path*. For a :class:`Maildir`
286 instance that behaves like instances of other :class:`Mailbox` subclasses, set
287 *factory* to ``None``.
289 Maildir is a directory-based mailbox format invented for the qmail mail transfer
290 agent and now widely supported by other programs. Messages in a Maildir mailbox
291 are stored in separate files within a common directory structure. This design
292 allows Maildir mailboxes to be accessed and modified by multiple unrelated
293 programs without data corruption, so file locking is unnecessary.
295 Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
296 :file:`new`, and :file:`cur`. Messages are created momentarily in the
297 :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to
298 finalize delivery. A mail user agent may subsequently move the message to the
299 :file:`cur` subdirectory and store information about the state of the message in
300 a special "info" section appended to its file name.
302 Folders of the style introduced by the Courier mail transfer agent are also
303 supported. Any subdirectory of the main mailbox is considered a folder if
304 ``'.'`` is the first character in its name. Folder names are represented by
305 :class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
306 mailbox but should not contain other folders. Instead, a logical nesting is
307 indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
311 The Maildir specification requires the use of a colon (``':'``) in certain
312 message file names. However, some operating systems do not permit this character
313 in file names, If you wish to use a Maildir-like format on such an operating
314 system, you should specify another character to use instead. The exclamation
315 point (``'!'``) is a popular choice. For example::
318 mailbox.Maildir.colon = '!'
320 The :attr:`colon` attribute may also be set on a per-instance basis.
322 :class:`Maildir` instances have all of the methods of :class:`Mailbox` in
323 addition to the following:
326 .. method:: Maildir.list_folders()
328 Return a list of the names of all folders.
331 .. method:: Maildir.get_folder(folder)
333 Return a :class:`Maildir` instance representing the folder whose name is
334 *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder does not
338 .. method:: Maildir.add_folder(folder)
340 Create a folder whose name is *folder* and return a :class:`Maildir` instance
344 .. method:: Maildir.remove_folder(folder)
346 Delete the folder whose name is *folder*. If the folder contains any messages, a
347 :exc:`NotEmptyError` exception will be raised and the folder will not be
351 .. method:: Maildir.clean()
353 Delete temporary files from the mailbox that have not been accessed in the last
354 36 hours. The Maildir specification says that mail-reading programs should do
357 Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
361 .. method:: Maildir.add(message)
362 Maildir.__setitem__(key, message)
367 These methods generate unique file names based upon the current process ID. When
368 using multiple threads, undetected name clashes may occur and cause corruption
369 of the mailbox unless threads are coordinated to avoid using these methods to
370 manipulate the same mailbox simultaneously.
373 .. method:: Maildir.flush()
375 All changes to Maildir mailboxes are immediately applied, so this method does
379 .. method:: Maildir.lock()
382 Maildir mailboxes do not support (or require) locking, so these methods do
386 .. method:: Maildir.close()
388 :class:`Maildir` instances do not keep any open files and the underlying
389 mailboxes do not support locking, so this method does nothing.
392 .. method:: Maildir.get_file(key)
394 Depending upon the host platform, it may not be possible to modify or remove the
395 underlying message while the returned file remains open.
400 `maildir man page from qmail <http://www.qmail.org/man/man5/maildir.html>`_
401 The original specification of the format.
403 `Using maildir format <http://cr.yp.to/proto/maildir.html>`_
404 Notes on Maildir by its inventor. Includes an updated name-creation scheme and
405 details on "info" semantics.
407 `maildir man page from Courier <http://www.courier-mta.org/maildir.html>`_
408 Another specification of the format. Describes a common extension for supporting
418 .. class:: mbox(path[, factory=None[, create=True]])
420 A subclass of :class:`Mailbox` for mailboxes in mbox format. Parameter *factory*
421 is a callable object that accepts a file-like message representation (which
422 behaves as if opened in binary mode) and returns a custom representation. If
423 *factory* is ``None``, :class:`mboxMessage` is used as the default message
424 representation. If *create* is ``True``, the mailbox is created if it does not
427 The mbox format is the classic format for storing mail on Unix systems. All
428 messages in an mbox mailbox are stored in a single file with the beginning of
429 each message indicated by a line whose first five characters are "From ".
431 Several variations of the mbox format exist to address perceived shortcomings in
432 the original. In the interest of compatibility, :class:`mbox` implements the
433 original format, which is sometimes referred to as :dfn:`mboxo`. This means that
434 the :mailheader:`Content-Length` header, if present, is ignored and that any
435 occurrences of "From " at the beginning of a line in a message body are
436 transformed to ">From " when storing the message, although occurrences of ">From
437 " are not transformed to "From " when reading the message.
439 Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
443 .. method:: mbox.get_file(key)
445 Using the file after calling :meth:`flush` or :meth:`close` on the :class:`mbox`
446 instance may yield unpredictable results or raise an exception.
449 .. method:: mbox.lock()
452 Three locking mechanisms are used---dot locking and, if available, the
453 :cfunc:`flock` and :cfunc:`lockf` system calls.
458 `mbox man page from qmail <http://www.qmail.org/man/man5/mbox.html>`_
459 A specification of the format and its variations.
461 `mbox man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mbox>`_
462 Another specification of the format, with details on locking.
464 `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <http://www.jwz.org/doc/content-length.html>`_
465 An argument for using the original mbox format rather than a variation.
467 `"mbox" is a family of several mutually incompatible mailbox formats <http://homepages.tesco.net./~J.deBoynePollard/FGA/mail-mbox-formats.html>`_
468 A history of mbox variations.
477 .. class:: MH(path[, factory=None[, create=True]])
479 A subclass of :class:`Mailbox` for mailboxes in MH format. Parameter *factory*
480 is a callable object that accepts a file-like message representation (which
481 behaves as if opened in binary mode) and returns a custom representation. If
482 *factory* is ``None``, :class:`MHMessage` is used as the default message
483 representation. If *create* is ``True``, the mailbox is created if it does not
486 MH is a directory-based mailbox format invented for the MH Message Handling
487 System, a mail user agent. Each message in an MH mailbox resides in its own
488 file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in
489 addition to messages. Folders may be nested indefinitely. MH mailboxes also
490 support :dfn:`sequences`, which are named lists used to logically group messages
491 without moving them to sub-folders. Sequences are defined in a file called
492 :file:`.mh_sequences` in each folder.
494 The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
495 emulate all of :program:`mh`'s behaviors. In particular, it does not modify and
496 is not affected by the :file:`context` or :file:`.mh_profile` files that are
497 used by :program:`mh` to store its state and configuration.
499 :class:`MH` instances have all of the methods of :class:`Mailbox` in addition to
503 .. method:: MH.list_folders()
505 Return a list of the names of all folders.
508 .. method:: MH.get_folder(folder)
510 Return an :class:`MH` instance representing the folder whose name is *folder*. A
511 :exc:`NoSuchMailboxError` exception is raised if the folder does not exist.
514 .. method:: MH.add_folder(folder)
516 Create a folder whose name is *folder* and return an :class:`MH` instance
520 .. method:: MH.remove_folder(folder)
522 Delete the folder whose name is *folder*. If the folder contains any messages, a
523 :exc:`NotEmptyError` exception will be raised and the folder will not be
527 .. method:: MH.get_sequences()
529 Return a dictionary of sequence names mapped to key lists. If there are no
530 sequences, the empty dictionary is returned.
533 .. method:: MH.set_sequences(sequences)
535 Re-define the sequences that exist in the mailbox based upon *sequences*, a
536 dictionary of names mapped to key lists, like returned by :meth:`get_sequences`.
539 .. method:: MH.pack()
541 Rename messages in the mailbox as necessary to eliminate gaps in numbering.
542 Entries in the sequences list are updated correspondingly.
546 Already-issued keys are invalidated by this operation and should not be
549 Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
553 .. method:: MH.remove(key)
557 These methods immediately delete the message. The MH convention of marking a
558 message for deletion by prepending a comma to its name is not used.
561 .. method:: MH.lock()
564 Three locking mechanisms are used---dot locking and, if available, the
565 :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking the
566 mailbox means locking the :file:`.mh_sequences` file and, only for the duration
567 of any operations that affect them, locking individual message files.
570 .. method:: MH.get_file(key)
572 Depending upon the host platform, it may not be possible to remove the
573 underlying message while the returned file remains open.
576 .. method:: MH.flush()
578 All changes to MH mailboxes are immediately applied, so this method does
582 .. method:: MH.close()
584 :class:`MH` instances do not keep any open files, so this method is equivalent
590 `nmh - Message Handling System <http://www.nongnu.org/nmh/>`_
591 Home page of :program:`nmh`, an updated version of the original :program:`mh`.
593 `MH & nmh: Email for Users & Programmers <http://www.ics.uci.edu/~mh/book/>`_
594 A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information
595 on the mailbox format.
604 .. class:: Babyl(path[, factory=None[, create=True]])
606 A subclass of :class:`Mailbox` for mailboxes in Babyl format. Parameter
607 *factory* is a callable object that accepts a file-like message representation
608 (which behaves as if opened in binary mode) and returns a custom representation.
609 If *factory* is ``None``, :class:`BabylMessage` is used as the default message
610 representation. If *create* is ``True``, the mailbox is created if it does not
613 Babyl is a single-file mailbox format used by the Rmail mail user agent included
614 with Emacs. The beginning of a message is indicated by a line containing the two
615 characters Control-Underscore (``'\037'``) and Control-L (``'\014'``). The end
616 of a message is indicated by the start of the next message or, in the case of
617 the last message, a line containing a Control-Underscore (``'\037'``)
620 Messages in a Babyl mailbox have two sets of headers, original headers and
621 so-called visible headers. Visible headers are typically a subset of the
622 original headers that have been reformatted or abridged to be more
623 attractive. Each message in a Babyl mailbox also has an accompanying list of
624 :dfn:`labels`, or short strings that record extra information about the message,
625 and a list of all user-defined labels found in the mailbox is kept in the Babyl
628 :class:`Babyl` instances have all of the methods of :class:`Mailbox` in addition
632 .. method:: Babyl.get_labels()
634 Return a list of the names of all user-defined labels used in the mailbox.
638 The actual messages are inspected to determine which labels exist in the mailbox
639 rather than consulting the list of labels in the Babyl options section, but the
640 Babyl section is updated whenever the mailbox is modified.
642 Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
646 .. method:: Babyl.get_file(key)
648 In Babyl mailboxes, the headers of a message are not stored contiguously with
649 the body of the message. To generate a file-like representation, the headers and
650 body are copied together into a :class:`StringIO` instance (from the
651 :mod:`StringIO` module), which has an API identical to that of a file. As a
652 result, the file-like object is truly independent of the underlying mailbox but
653 does not save memory compared to a string representation.
656 .. method:: Babyl.lock()
659 Three locking mechanisms are used---dot locking and, if available, the
660 :cfunc:`flock` and :cfunc:`lockf` system calls.
665 `Format of Version 5 Babyl Files <http://quimby.gnus.org/notes/BABYL>`_
666 A specification of the Babyl format.
668 `Reading Mail with Rmail <http://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html>`_
669 The Rmail manual, with some information on Babyl semantics.
678 .. class:: MMDF(path[, factory=None[, create=True]])
680 A subclass of :class:`Mailbox` for mailboxes in MMDF format. Parameter *factory*
681 is a callable object that accepts a file-like message representation (which
682 behaves as if opened in binary mode) and returns a custom representation. If
683 *factory* is ``None``, :class:`MMDFMessage` is used as the default message
684 representation. If *create* is ``True``, the mailbox is created if it does not
687 MMDF is a single-file mailbox format invented for the Multichannel Memorandum
688 Distribution Facility, a mail transfer agent. Each message is in the same form
689 as an mbox message but is bracketed before and after by lines containing four
690 Control-A (``'\001'``) characters. As with the mbox format, the beginning of
691 each message is indicated by a line whose first five characters are "From ", but
692 additional occurrences of "From " are not transformed to ">From " when storing
693 messages because the extra message separator lines prevent mistaking such
694 occurrences for the starts of subsequent messages.
696 Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
700 .. method:: MMDF.get_file(key)
702 Using the file after calling :meth:`flush` or :meth:`close` on the :class:`MMDF`
703 instance may yield unpredictable results or raise an exception.
706 .. method:: MMDF.lock()
709 Three locking mechanisms are used---dot locking and, if available, the
710 :cfunc:`flock` and :cfunc:`lockf` system calls.
715 `mmdf man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mmdf>`_
716 A specification of MMDF format from the documentation of tin, a newsreader.
718 `MMDF <http://en.wikipedia.org/wiki/MMDF>`_
719 A Wikipedia article describing the Multichannel Memorandum Distribution
723 .. _mailbox-message-objects:
725 :class:`Message` objects
726 ------------------------
729 .. class:: Message([message])
731 A subclass of the :mod:`email.Message` module's :class:`Message`. Subclasses of
732 :class:`mailbox.Message` add mailbox-format-specific state and behavior.
734 If *message* is omitted, the new instance is created in a default, empty state.
735 If *message* is an :class:`email.Message.Message` instance, its contents are
736 copied; furthermore, any format-specific information is converted insofar as
737 possible if *message* is a :class:`Message` instance. If *message* is a string
738 or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
741 The format-specific state and behaviors offered by subclasses vary, but in
742 general it is only the properties that are not specific to a particular mailbox
743 that are supported (although presumably the properties are specific to a
744 particular mailbox format). For example, file offsets for single-file mailbox
745 formats and file names for directory-based mailbox formats are not retained,
746 because they are only applicable to the original mailbox. But state such as
747 whether a message has been read by the user or marked as important is retained,
748 because it applies to the message itself.
750 There is no requirement that :class:`Message` instances be used to represent
751 messages retrieved using :class:`Mailbox` instances. In some situations, the
752 time and memory required to generate :class:`Message` representations might not
753 not acceptable. For such situations, :class:`Mailbox` instances also offer
754 string and file-like representations, and a custom message factory may be
755 specified when a :class:`Mailbox` instance is initialized.
758 .. _mailbox-maildirmessage:
760 :class:`MaildirMessage`
761 ^^^^^^^^^^^^^^^^^^^^^^^
764 .. class:: MaildirMessage([message])
766 A message with Maildir-specific behaviors. Parameter *message* has the same
767 meaning as with the :class:`Message` constructor.
769 Typically, a mail user agent application moves all of the messages in the
770 :file:`new` subdirectory to the :file:`cur` subdirectory after the first time
771 the user opens and closes the mailbox, recording that the messages are old
772 whether or not they've actually been read. Each message in :file:`cur` has an
773 "info" section added to its file name to store information about its state.
774 (Some mail readers may also add an "info" section to messages in :file:`new`.)
775 The "info" section may take one of two forms: it may contain "2," followed by a
776 list of standardized flags (e.g., "2,FR") or it may contain "1," followed by
777 so-called experimental information. Standard flags for Maildir messages are as
780 +------+---------+--------------------------------+
781 | Flag | Meaning | Explanation |
782 +======+=========+================================+
783 | D | Draft | Under composition |
784 +------+---------+--------------------------------+
785 | F | Flagged | Marked as important |
786 +------+---------+--------------------------------+
787 | P | Passed | Forwarded, resent, or bounced |
788 +------+---------+--------------------------------+
789 | R | Replied | Replied to |
790 +------+---------+--------------------------------+
792 +------+---------+--------------------------------+
793 | T | Trashed | Marked for subsequent deletion |
794 +------+---------+--------------------------------+
796 :class:`MaildirMessage` instances offer the following methods:
799 .. method:: MaildirMessage.get_subdir()
801 Return either "new" (if the message should be stored in the :file:`new`
802 subdirectory) or "cur" (if the message should be stored in the :file:`cur`
807 A message is typically moved from :file:`new` to :file:`cur` after its mailbox
808 has been accessed, whether or not the message is has been read. A message
809 ``msg`` has been read if ``"S" in msg.get_flags()`` is ``True``.
812 .. method:: MaildirMessage.set_subdir(subdir)
814 Set the subdirectory the message should be stored in. Parameter *subdir* must be
815 either "new" or "cur".
818 .. method:: MaildirMessage.get_flags()
820 Return a string specifying the flags that are currently set. If the message
821 complies with the standard Maildir format, the result is the concatenation in
822 alphabetical order of zero or one occurrence of each of ``'D'``, ``'F'``,
823 ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string is returned if no flags
824 are set or if "info" contains experimental semantics.
827 .. method:: MaildirMessage.set_flags(flags)
829 Set the flags specified by *flags* and unset all others.
832 .. method:: MaildirMessage.add_flag(flag)
834 Set the flag(s) specified by *flag* without changing other flags. To add more
835 than one flag at a time, *flag* may be a string of more than one character. The
836 current "info" is overwritten whether or not it contains experimental
837 information rather than flags.
840 .. method:: MaildirMessage.remove_flag(flag)
842 Unset the flag(s) specified by *flag* without changing other flags. To remove
843 more than one flag at a time, *flag* maybe a string of more than one character.
844 If "info" contains experimental information rather than flags, the current
845 "info" is not modified.
848 .. method:: MaildirMessage.get_date()
850 Return the delivery date of the message as a floating-point number representing
851 seconds since the epoch.
854 .. method:: MaildirMessage.set_date(date)
856 Set the delivery date of the message to *date*, a floating-point number
857 representing seconds since the epoch.
860 .. method:: MaildirMessage.get_info()
862 Return a string containing the "info" for a message. This is useful for
863 accessing and modifying "info" that is experimental (i.e., not a list of flags).
866 .. method:: MaildirMessage.set_info(info)
868 Set "info" to *info*, which should be a string.
870 When a :class:`MaildirMessage` instance is created based upon an
871 :class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
872 and :mailheader:`X-Status` headers are omitted and the following conversions
875 +--------------------+----------------------------------------------+
876 | Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
878 +====================+==============================================+
879 | "cur" subdirectory | O flag |
880 +--------------------+----------------------------------------------+
882 +--------------------+----------------------------------------------+
884 +--------------------+----------------------------------------------+
886 +--------------------+----------------------------------------------+
888 +--------------------+----------------------------------------------+
890 When a :class:`MaildirMessage` instance is created based upon an
891 :class:`MHMessage` instance, the following conversions take place:
893 +-------------------------------+--------------------------+
894 | Resulting state | :class:`MHMessage` state |
895 +===============================+==========================+
896 | "cur" subdirectory | "unseen" sequence |
897 +-------------------------------+--------------------------+
898 | "cur" subdirectory and S flag | no "unseen" sequence |
899 +-------------------------------+--------------------------+
900 | F flag | "flagged" sequence |
901 +-------------------------------+--------------------------+
902 | R flag | "replied" sequence |
903 +-------------------------------+--------------------------+
905 When a :class:`MaildirMessage` instance is created based upon a
906 :class:`BabylMessage` instance, the following conversions take place:
908 +-------------------------------+-------------------------------+
909 | Resulting state | :class:`BabylMessage` state |
910 +===============================+===============================+
911 | "cur" subdirectory | "unseen" label |
912 +-------------------------------+-------------------------------+
913 | "cur" subdirectory and S flag | no "unseen" label |
914 +-------------------------------+-------------------------------+
915 | P flag | "forwarded" or "resent" label |
916 +-------------------------------+-------------------------------+
917 | R flag | "answered" label |
918 +-------------------------------+-------------------------------+
919 | T flag | "deleted" label |
920 +-------------------------------+-------------------------------+
923 .. _mailbox-mboxmessage:
929 .. class:: mboxMessage([message])
931 A message with mbox-specific behaviors. Parameter *message* has the same meaning
932 as with the :class:`Message` constructor.
934 Messages in an mbox mailbox are stored together in a single file. The sender's
935 envelope address and the time of delivery are typically stored in a line
936 beginning with "From " that is used to indicate the start of a message, though
937 there is considerable variation in the exact format of this data among mbox
938 implementations. Flags that indicate the state of the message, such as whether
939 it has been read or marked as important, are typically stored in
940 :mailheader:`Status` and :mailheader:`X-Status` headers.
942 Conventional flags for mbox messages are as follows:
944 +------+----------+--------------------------------+
945 | Flag | Meaning | Explanation |
946 +======+==========+================================+
948 +------+----------+--------------------------------+
949 | O | Old | Previously detected by MUA |
950 +------+----------+--------------------------------+
951 | D | Deleted | Marked for subsequent deletion |
952 +------+----------+--------------------------------+
953 | F | Flagged | Marked as important |
954 +------+----------+--------------------------------+
955 | A | Answered | Replied to |
956 +------+----------+--------------------------------+
958 The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
959 "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
960 flags and headers typically appear in the order mentioned.
962 :class:`mboxMessage` instances offer the following methods:
965 .. method:: mboxMessage.get_from()
967 Return a string representing the "From " line that marks the start of the
968 message in an mbox mailbox. The leading "From " and the trailing newline are
972 .. method:: mboxMessage.set_from(from_[, time_=None])
974 Set the "From " line to *from_*, which should be specified without a leading
975 "From " or trailing newline. For convenience, *time_* may be specified and will
976 be formatted appropriately and appended to *from_*. If *time_* is specified, it
977 should be a :class:`struct_time` instance, a tuple suitable for passing to
978 :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`).
981 .. method:: mboxMessage.get_flags()
983 Return a string specifying the flags that are currently set. If the message
984 complies with the conventional format, the result is the concatenation in the
985 following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``,
986 ``'F'``, and ``'A'``.
989 .. method:: mboxMessage.set_flags(flags)
991 Set the flags specified by *flags* and unset all others. Parameter *flags*
992 should be the concatenation in any order of zero or more occurrences of each of
993 ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
996 .. method:: mboxMessage.add_flag(flag)
998 Set the flag(s) specified by *flag* without changing other flags. To add more
999 than one flag at a time, *flag* may be a string of more than one character.
1002 .. method:: mboxMessage.remove_flag(flag)
1004 Unset the flag(s) specified by *flag* without changing other flags. To remove
1005 more than one flag at a time, *flag* maybe a string of more than one character.
1007 When an :class:`mboxMessage` instance is created based upon a
1008 :class:`MaildirMessage` instance, a "From " line is generated based upon the
1009 :class:`MaildirMessage` instance's delivery date, and the following conversions
1012 +-----------------+-------------------------------+
1013 | Resulting state | :class:`MaildirMessage` state |
1014 +=================+===============================+
1016 +-----------------+-------------------------------+
1017 | O flag | "cur" subdirectory |
1018 +-----------------+-------------------------------+
1020 +-----------------+-------------------------------+
1022 +-----------------+-------------------------------+
1024 +-----------------+-------------------------------+
1026 When an :class:`mboxMessage` instance is created based upon an
1027 :class:`MHMessage` instance, the following conversions take place:
1029 +-------------------+--------------------------+
1030 | Resulting state | :class:`MHMessage` state |
1031 +===================+==========================+
1032 | R flag and O flag | no "unseen" sequence |
1033 +-------------------+--------------------------+
1034 | O flag | "unseen" sequence |
1035 +-------------------+--------------------------+
1036 | F flag | "flagged" sequence |
1037 +-------------------+--------------------------+
1038 | A flag | "replied" sequence |
1039 +-------------------+--------------------------+
1041 When an :class:`mboxMessage` instance is created based upon a
1042 :class:`BabylMessage` instance, the following conversions take place:
1044 +-------------------+-----------------------------+
1045 | Resulting state | :class:`BabylMessage` state |
1046 +===================+=============================+
1047 | R flag and O flag | no "unseen" label |
1048 +-------------------+-----------------------------+
1049 | O flag | "unseen" label |
1050 +-------------------+-----------------------------+
1051 | D flag | "deleted" label |
1052 +-------------------+-----------------------------+
1053 | A flag | "answered" label |
1054 +-------------------+-----------------------------+
1056 When a :class:`Message` instance is created based upon an :class:`MMDFMessage`
1057 instance, the "From " line is copied and all flags directly correspond:
1059 +-----------------+----------------------------+
1060 | Resulting state | :class:`MMDFMessage` state |
1061 +=================+============================+
1063 +-----------------+----------------------------+
1065 +-----------------+----------------------------+
1067 +-----------------+----------------------------+
1069 +-----------------+----------------------------+
1071 +-----------------+----------------------------+
1074 .. _mailbox-mhmessage:
1080 .. class:: MHMessage([message])
1082 A message with MH-specific behaviors. Parameter *message* has the same meaning
1083 as with the :class:`Message` constructor.
1085 MH messages do not support marks or flags in the traditional sense, but they do
1086 support sequences, which are logical groupings of arbitrary messages. Some mail
1087 reading programs (although not the standard :program:`mh` and :program:`nmh`)
1088 use sequences in much the same way flags are used with other formats, as
1091 +----------+------------------------------------------+
1092 | Sequence | Explanation |
1093 +==========+==========================================+
1094 | unseen | Not read, but previously detected by MUA |
1095 +----------+------------------------------------------+
1096 | replied | Replied to |
1097 +----------+------------------------------------------+
1098 | flagged | Marked as important |
1099 +----------+------------------------------------------+
1101 :class:`MHMessage` instances offer the following methods:
1104 .. method:: MHMessage.get_sequences()
1106 Return a list of the names of sequences that include this message.
1109 .. method:: MHMessage.set_sequences(sequences)
1111 Set the list of sequences that include this message.
1114 .. method:: MHMessage.add_sequence(sequence)
1116 Add *sequence* to the list of sequences that include this message.
1119 .. method:: MHMessage.remove_sequence(sequence)
1121 Remove *sequence* from the list of sequences that include this message.
1123 When an :class:`MHMessage` instance is created based upon a
1124 :class:`MaildirMessage` instance, the following conversions take place:
1126 +--------------------+-------------------------------+
1127 | Resulting state | :class:`MaildirMessage` state |
1128 +====================+===============================+
1129 | "unseen" sequence | no S flag |
1130 +--------------------+-------------------------------+
1131 | "replied" sequence | R flag |
1132 +--------------------+-------------------------------+
1133 | "flagged" sequence | F flag |
1134 +--------------------+-------------------------------+
1136 When an :class:`MHMessage` instance is created based upon an
1137 :class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1138 and :mailheader:`X-Status` headers are omitted and the following conversions
1141 +--------------------+----------------------------------------------+
1142 | Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1144 +====================+==============================================+
1145 | "unseen" sequence | no R flag |
1146 +--------------------+----------------------------------------------+
1147 | "replied" sequence | A flag |
1148 +--------------------+----------------------------------------------+
1149 | "flagged" sequence | F flag |
1150 +--------------------+----------------------------------------------+
1152 When an :class:`MHMessage` instance is created based upon a
1153 :class:`BabylMessage` instance, the following conversions take place:
1155 +--------------------+-----------------------------+
1156 | Resulting state | :class:`BabylMessage` state |
1157 +====================+=============================+
1158 | "unseen" sequence | "unseen" label |
1159 +--------------------+-----------------------------+
1160 | "replied" sequence | "answered" label |
1161 +--------------------+-----------------------------+
1164 .. _mailbox-babylmessage:
1166 :class:`BabylMessage`
1167 ^^^^^^^^^^^^^^^^^^^^^
1170 .. class:: BabylMessage([message])
1172 A message with Babyl-specific behaviors. Parameter *message* has the same
1173 meaning as with the :class:`Message` constructor.
1175 Certain message labels, called :dfn:`attributes`, are defined by convention to
1176 have special meanings. The attributes are as follows:
1178 +-----------+------------------------------------------+
1179 | Label | Explanation |
1180 +===========+==========================================+
1181 | unseen | Not read, but previously detected by MUA |
1182 +-----------+------------------------------------------+
1183 | deleted | Marked for subsequent deletion |
1184 +-----------+------------------------------------------+
1185 | filed | Copied to another file or mailbox |
1186 +-----------+------------------------------------------+
1187 | answered | Replied to |
1188 +-----------+------------------------------------------+
1189 | forwarded | Forwarded |
1190 +-----------+------------------------------------------+
1191 | edited | Modified by the user |
1192 +-----------+------------------------------------------+
1194 +-----------+------------------------------------------+
1196 By default, Rmail displays only visible headers. The :class:`BabylMessage`
1197 class, though, uses the original headers because they are more complete. Visible
1198 headers may be accessed explicitly if desired.
1200 :class:`BabylMessage` instances offer the following methods:
1203 .. method:: BabylMessage.get_labels()
1205 Return a list of labels on the message.
1208 .. method:: BabylMessage.set_labels(labels)
1210 Set the list of labels on the message to *labels*.
1213 .. method:: BabylMessage.add_label(label)
1215 Add *label* to the list of labels on the message.
1218 .. method:: BabylMessage.remove_label(label)
1220 Remove *label* from the list of labels on the message.
1223 .. method:: BabylMessage.get_visible()
1225 Return an :class:`Message` instance whose headers are the message's visible
1226 headers and whose body is empty.
1229 .. method:: BabylMessage.set_visible(visible)
1231 Set the message's visible headers to be the same as the headers in *message*.
1232 Parameter *visible* should be a :class:`Message` instance, an
1233 :class:`email.Message.Message` instance, a string, or a file-like object (which
1234 should be open in text mode).
1237 .. method:: BabylMessage.update_visible()
1239 When a :class:`BabylMessage` instance's original headers are modified, the
1240 visible headers are not automatically modified to correspond. This method
1241 updates the visible headers as follows: each visible header with a corresponding
1242 original header is set to the value of the original header, each visible header
1243 without a corresponding original header is removed, and any of
1244 :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`,
1245 :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are present
1246 in the original headers but not the visible headers are added to the visible
1249 When a :class:`BabylMessage` instance is created based upon a
1250 :class:`MaildirMessage` instance, the following conversions take place:
1252 +-------------------+-------------------------------+
1253 | Resulting state | :class:`MaildirMessage` state |
1254 +===================+===============================+
1255 | "unseen" label | no S flag |
1256 +-------------------+-------------------------------+
1257 | "deleted" label | T flag |
1258 +-------------------+-------------------------------+
1259 | "answered" label | R flag |
1260 +-------------------+-------------------------------+
1261 | "forwarded" label | P flag |
1262 +-------------------+-------------------------------+
1264 When a :class:`BabylMessage` instance is created based upon an
1265 :class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1266 and :mailheader:`X-Status` headers are omitted and the following conversions
1269 +------------------+----------------------------------------------+
1270 | Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1272 +==================+==============================================+
1273 | "unseen" label | no R flag |
1274 +------------------+----------------------------------------------+
1275 | "deleted" label | D flag |
1276 +------------------+----------------------------------------------+
1277 | "answered" label | A flag |
1278 +------------------+----------------------------------------------+
1280 When a :class:`BabylMessage` instance is created based upon an
1281 :class:`MHMessage` instance, the following conversions take place:
1283 +------------------+--------------------------+
1284 | Resulting state | :class:`MHMessage` state |
1285 +==================+==========================+
1286 | "unseen" label | "unseen" sequence |
1287 +------------------+--------------------------+
1288 | "answered" label | "replied" sequence |
1289 +------------------+--------------------------+
1292 .. _mailbox-mmdfmessage:
1294 :class:`MMDFMessage`
1295 ^^^^^^^^^^^^^^^^^^^^
1298 .. class:: MMDFMessage([message])
1300 A message with MMDF-specific behaviors. Parameter *message* has the same meaning
1301 as with the :class:`Message` constructor.
1303 As with message in an mbox mailbox, MMDF messages are stored with the sender's
1304 address and the delivery date in an initial line beginning with "From ".
1305 Likewise, flags that indicate the state of the message are typically stored in
1306 :mailheader:`Status` and :mailheader:`X-Status` headers.
1308 Conventional flags for MMDF messages are identical to those of mbox message and
1311 +------+----------+--------------------------------+
1312 | Flag | Meaning | Explanation |
1313 +======+==========+================================+
1315 +------+----------+--------------------------------+
1316 | O | Old | Previously detected by MUA |
1317 +------+----------+--------------------------------+
1318 | D | Deleted | Marked for subsequent deletion |
1319 +------+----------+--------------------------------+
1320 | F | Flagged | Marked as important |
1321 +------+----------+--------------------------------+
1322 | A | Answered | Replied to |
1323 +------+----------+--------------------------------+
1325 The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
1326 "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
1327 flags and headers typically appear in the order mentioned.
1329 :class:`MMDFMessage` instances offer the following methods, which are identical
1330 to those offered by :class:`mboxMessage`:
1333 .. method:: MMDFMessage.get_from()
1335 Return a string representing the "From " line that marks the start of the
1336 message in an mbox mailbox. The leading "From " and the trailing newline are
1340 .. method:: MMDFMessage.set_from(from_[, time_=None])
1342 Set the "From " line to *from_*, which should be specified without a leading
1343 "From " or trailing newline. For convenience, *time_* may be specified and will
1344 be formatted appropriately and appended to *from_*. If *time_* is specified, it
1345 should be a :class:`struct_time` instance, a tuple suitable for passing to
1346 :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`).
1349 .. method:: MMDFMessage.get_flags()
1351 Return a string specifying the flags that are currently set. If the message
1352 complies with the conventional format, the result is the concatenation in the
1353 following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``,
1354 ``'F'``, and ``'A'``.
1357 .. method:: MMDFMessage.set_flags(flags)
1359 Set the flags specified by *flags* and unset all others. Parameter *flags*
1360 should be the concatenation in any order of zero or more occurrences of each of
1361 ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1364 .. method:: MMDFMessage.add_flag(flag)
1366 Set the flag(s) specified by *flag* without changing other flags. To add more
1367 than one flag at a time, *flag* may be a string of more than one character.
1370 .. method:: MMDFMessage.remove_flag(flag)
1372 Unset the flag(s) specified by *flag* without changing other flags. To remove
1373 more than one flag at a time, *flag* maybe a string of more than one character.
1375 When an :class:`MMDFMessage` instance is created based upon a
1376 :class:`MaildirMessage` instance, a "From " line is generated based upon the
1377 :class:`MaildirMessage` instance's delivery date, and the following conversions
1380 +-----------------+-------------------------------+
1381 | Resulting state | :class:`MaildirMessage` state |
1382 +=================+===============================+
1384 +-----------------+-------------------------------+
1385 | O flag | "cur" subdirectory |
1386 +-----------------+-------------------------------+
1388 +-----------------+-------------------------------+
1390 +-----------------+-------------------------------+
1392 +-----------------+-------------------------------+
1394 When an :class:`MMDFMessage` instance is created based upon an
1395 :class:`MHMessage` instance, the following conversions take place:
1397 +-------------------+--------------------------+
1398 | Resulting state | :class:`MHMessage` state |
1399 +===================+==========================+
1400 | R flag and O flag | no "unseen" sequence |
1401 +-------------------+--------------------------+
1402 | O flag | "unseen" sequence |
1403 +-------------------+--------------------------+
1404 | F flag | "flagged" sequence |
1405 +-------------------+--------------------------+
1406 | A flag | "replied" sequence |
1407 +-------------------+--------------------------+
1409 When an :class:`MMDFMessage` instance is created based upon a
1410 :class:`BabylMessage` instance, the following conversions take place:
1412 +-------------------+-----------------------------+
1413 | Resulting state | :class:`BabylMessage` state |
1414 +===================+=============================+
1415 | R flag and O flag | no "unseen" label |
1416 +-------------------+-----------------------------+
1417 | O flag | "unseen" label |
1418 +-------------------+-----------------------------+
1419 | D flag | "deleted" label |
1420 +-------------------+-----------------------------+
1421 | A flag | "answered" label |
1422 +-------------------+-----------------------------+
1424 When an :class:`MMDFMessage` instance is created based upon an
1425 :class:`mboxMessage` instance, the "From " line is copied and all flags directly
1428 +-----------------+----------------------------+
1429 | Resulting state | :class:`mboxMessage` state |
1430 +=================+============================+
1432 +-----------------+----------------------------+
1434 +-----------------+----------------------------+
1436 +-----------------+----------------------------+
1438 +-----------------+----------------------------+
1440 +-----------------+----------------------------+
1446 The following exception classes are defined in the :mod:`mailbox` module:
1451 The based class for all other module-specific exceptions.
1454 .. class:: NoSuchMailboxError()
1456 Raised when a mailbox is expected but is not found, such as when instantiating a
1457 :class:`Mailbox` subclass with a path that does not exist (and with the *create*
1458 parameter set to ``False``), or when opening a folder that does not exist.
1461 .. class:: NotEmptyErrorError()
1463 Raised when a mailbox is not empty but is expected to be, such as when deleting
1464 a folder that contains messages.
1467 .. class:: ExternalClashError()
1469 Raised when some mailbox-related condition beyond the control of the program
1470 causes it to be unable to proceed, such as when failing to acquire a lock that
1471 another program already holds a lock, or when a uniquely-generated file name
1475 .. class:: FormatError()
1477 Raised when the data in a file cannot be parsed, such as when an :class:`MH`
1478 instance attempts to read a corrupted :file:`.mh_sequences` file.
1481 .. _mailbox-deprecated:
1483 Deprecated classes and methods
1484 ------------------------------
1486 Older versions of the :mod:`mailbox` module do not support modification of
1487 mailboxes, such as adding or removing message, and do not provide classes to
1488 represent format-specific message properties. For backward compatibility, the
1489 older mailbox classes are still available, but the newer classes should be used
1490 in preference to them.
1492 Older mailbox objects support only iteration and provide a single public method:
1495 .. method:: oldmailbox.next()
1497 Return the next message in the mailbox, created with the optional *factory*
1498 argument passed into the mailbox object's constructor. By default this is an
1499 :class:`rfc822.Message` object (see the :mod:`rfc822` module). Depending on the
1500 mailbox implementation the *fp* attribute of this object may be a true file
1501 object or a class instance simulating a file object, taking care of things like
1502 message boundaries if multiple mail messages are contained in a single file,
1503 etc. If no more messages are available, this method returns ``None``.
1505 Most of the older mailbox classes have names that differ from the current
1506 mailbox class names, except for :class:`Maildir`. For this reason, the new
1507 :class:`Maildir` class defines a :meth:`next` method and its constructor differs
1508 slightly from those of the other new mailbox classes.
1510 The older mailbox classes whose names are not the same as their newer
1511 counterparts are as follows:
1514 .. class:: UnixMailbox(fp[, factory])
1516 Access to a classic Unix-style mailbox, where all messages are contained in a
1517 single file and separated by ``From`` (a.k.a. ``From_``) lines. The file object
1518 *fp* points to the mailbox file. The optional *factory* parameter is a callable
1519 that should create new message objects. *factory* is called with one argument,
1520 *fp* by the :meth:`next` method of the mailbox object. The default is the
1521 :class:`rfc822.Message` class (see the :mod:`rfc822` module -- and the note
1526 For reasons of this module's internal implementation, you will probably want to
1527 open the *fp* object in binary mode. This is especially important on Windows.
1529 For maximum portability, messages in a Unix-style mailbox are separated by any
1530 line that begins exactly with the string ``'From '`` (note the trailing space)
1531 if preceded by exactly two newlines. Because of the wide-range of variations in
1532 practice, nothing else on the ``From_`` line should be considered. However, the
1533 current implementation doesn't check for the leading two newlines. This is
1534 usually fine for most applications.
1536 The :class:`UnixMailbox` class implements a more strict version of ``From_``
1537 line checking, using a regular expression that usually correctly matched
1538 ``From_`` delimiters. It considers delimiter line to be separated by ``From
1539 name time`` lines. For maximum portability, use the
1540 :class:`PortableUnixMailbox` class instead. This class is identical to
1541 :class:`UnixMailbox` except that individual messages are separated by only
1545 .. class:: PortableUnixMailbox(fp[, factory])
1547 A less-strict version of :class:`UnixMailbox`, which considers only the ``From``
1548 at the beginning of the line separating messages. The "*name* *time*" portion
1549 of the From line is ignored, to protect against some variations that are
1550 observed in practice. This works since lines in the message which begin with
1551 ``'From '`` are quoted by mail handling software at delivery-time.
1554 .. class:: MmdfMailbox(fp[, factory])
1556 Access an MMDF-style mailbox, where all messages are contained in a single file
1557 and separated by lines consisting of 4 control-A characters. The file object
1558 *fp* points to the mailbox file. Optional *factory* is as with the
1559 :class:`UnixMailbox` class.
1562 .. class:: MHMailbox(dirname[, factory])
1564 Access an MH mailbox, a directory with each message in a separate file with a
1565 numeric name. The name of the mailbox directory is passed in *dirname*.
1566 *factory* is as with the :class:`UnixMailbox` class.
1569 .. class:: BabylMailbox(fp[, factory])
1571 Access a Babyl mailbox, which is similar to an MMDF mailbox. In Babyl format,
1572 each message has two sets of headers, the *original* headers and the *visible*
1573 headers. The original headers appear before a line containing only ``'*** EOOH
1574 ***'`` (End-Of-Original-Headers) and the visible headers appear after the
1575 ``EOOH`` line. Babyl-compliant mail readers will show you only the visible
1576 headers, and :class:`BabylMailbox` objects will return messages containing only
1577 the visible headers. You'll have to do your own parsing of the mailbox file to
1578 get at the original headers. Mail messages start with the EOOH line and end
1579 with a line containing only ``'\037\014'``. *factory* is as with the
1580 :class:`UnixMailbox` class.
1582 If you wish to use the older mailbox classes with the :mod:`email` module rather
1583 than the deprecated :mod:`rfc822` module, you can do so as follows::
1591 return email.message_from_file(fp)
1592 except email.Errors.MessageParseError:
1593 # Don't return None since that will
1594 # stop the mailbox iterator
1597 mbox = mailbox.UnixMailbox(fp, msgfactory)
1599 Alternatively, if you know your mailbox contains only well-formed MIME messages,
1600 you can simplify this to::
1605 mbox = mailbox.UnixMailbox(fp, email.message_from_file)
1608 .. _mailbox-examples:
1613 A simple example of printing the subjects of all messages in a mailbox that seem
1617 for message in mailbox.mbox('~/mbox'):
1618 subject = message['subject'] # Could possibly be None.
1619 if subject and 'python' in subject.lower():
1622 To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
1623 format-specific information that can be converted::
1626 destination = mailbox.MH('~/Mail')
1628 for message in mailbox.Babyl('~/RMAIL'):
1629 destination.add(mailbox.MHMessage(message))
1631 destination.unlock()
1633 This example sorts mail from several mailing lists into different mailboxes,
1634 being careful to avoid mail corruption due to concurrent modification by other
1635 programs, mail loss due to interruption of the program, or premature termination
1636 due to malformed messages in the mailbox::
1641 list_names = ('python-list', 'python-dev', 'python-bugs')
1643 boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names)
1644 inbox = mailbox.Maildir('~/Maildir', factory=None)
1646 for key in inbox.iterkeys():
1648 message = inbox[key]
1649 except email.Errors.MessageParseError:
1650 continue # The message is malformed. Just leave it.
1652 for name in list_names:
1653 list_id = message['list-id']
1654 if list_id and name in list_id:
1655 # Get mailbox to use
1658 # Write copy to disk before removing original.
1659 # If there's a crash, you might duplicate a message, but
1660 # that's better than losing a message completely.
1666 # Remove original message
1671 break # Found destination, so stop looking.
1673 for box in boxes.itervalues():