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
40
corresponding to messages. Keys are issued by the :class:`Mailbox` instance
41
with which they will be used and are only meaningful to that :class:`Mailbox`
42
instance. A key continues to identify a message even if the corresponding
43
message is modified, such as by replacing it with another message.
45
Messages may be added to a :class:`Mailbox` instance using the set-like
46
method :meth:`add` and removed using a ``del`` statement or the set-like
47
methods :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
53
:class:`Mailbox` instance, the provided message representation's contents are
54
copied. In neither case is a reference to the message representation kept by
55
the :class:`Mailbox` instance.
57
The default :class:`Mailbox` iterator iterates over message representations,
58
not keys as the default dictionary iterator does. Moreover, modification of a
59
mailbox during iteration is safe and well-defined. Messages added to the
60
mailbox after an iterator is created will not be seen by the
61
iterator. Messages removed from the mailbox before the iterator yields them
62
will be silently skipped, though using a key from an iterator may result in a
63
:exc:`KeyError` exception if the corresponding message is subsequently
68
Be very cautious when modifying mailboxes that might be simultaneously
69
changed by some other process. The safest mailbox format to use for such
70
tasks is Maildir; try to avoid using single-file formats such as mbox for
71
concurrent writing. If you're modifying a mailbox, you *must* lock it by
72
calling the :meth:`lock` and :meth:`unlock` methods *before* reading any
73
messages in the file or making any changes by adding or deleting a
74
message. Failing to lock the mailbox runs the risk of losing messages or
75
corrupting the entire mailbox.
77
:class:`Mailbox` instances have the following methods:
80
.. method:: add(message)
82
Add *message* to the mailbox and return the key that has been assigned to
85
Parameter *message* may be a :class:`Message` instance, an
86
:class:`email.Message.Message` instance, a string, or a file-like object
87
(which should be open in text mode). If *message* is an instance of the
88
appropriate format-specific :class:`Message` subclass (e.g., if it's an
89
:class:`mboxMessage` instance and this is an :class:`mbox` instance), its
90
format-specific information is used. Otherwise, reasonable defaults for
91
format-specific information are used.
94
.. method:: remove(key)
98
Delete the message corresponding to *key* from the mailbox.
100
If no such message exists, a :exc:`KeyError` exception is raised if the
101
method was called as :meth:`remove` or :meth:`__delitem__` but no
102
exception is raised if the method was called as :meth:`discard`. The
103
behavior of :meth:`discard` may be preferred if the underlying mailbox
104
format supports concurrent modification by other processes.
107
.. method:: __setitem__(key, message)
109
Replace the message corresponding to *key* with *message*. Raise a
110
:exc:`KeyError` exception if no message already corresponds to *key*.
112
As with :meth:`add`, parameter *message* may be a :class:`Message`
113
instance, an :class:`email.Message.Message` instance, a string, or a
114
file-like object (which should be open in text mode). If *message* is an
115
instance of the appropriate format-specific :class:`Message` subclass
116
(e.g., if it's an :class:`mboxMessage` instance and this is an
117
:class:`mbox` instance), its format-specific information is
118
used. Otherwise, the format-specific information of the message that
119
currently corresponds to *key* is left unchanged.
122
.. method:: iterkeys()
125
Return an iterator over all keys if called as :meth:`iterkeys` or return a
126
list of keys if called as :meth:`keys`.
129
.. method:: itervalues()
133
Return an iterator over representations of all messages if called as
134
:meth:`itervalues` or :meth:`__iter__` or return a list of such
135
representations if called as :meth:`values`. The messages are represented
136
as instances of the appropriate format-specific :class:`Message` subclass
137
unless a custom message factory was specified when the :class:`Mailbox`
138
instance was initialized.
142
The behavior of :meth:`__iter__` is unlike that of dictionaries, which
146
.. method:: iteritems()
149
Return an iterator over (*key*, *message*) pairs, where *key* is a key and
150
*message* is a message representation, if called as :meth:`iteritems` or
151
return a list of such pairs if called as :meth:`items`. The messages are
152
represented as instances of the appropriate format-specific
153
:class:`Message` subclass unless a custom message factory was specified
154
when the :class:`Mailbox` instance was initialized.
157
.. method:: get(key[, default=None])
160
Return a representation of the message corresponding to *key*. If no such
161
message exists, *default* is returned if the method was called as
162
:meth:`get` and a :exc:`KeyError` exception is raised if the method was
163
called as :meth:`__getitem__`. The message is represented as an instance
164
of the appropriate format-specific :class:`Message` subclass unless a
165
custom message factory was specified when the :class:`Mailbox` instance
169
.. method:: get_message(key)
171
Return a representation of the message corresponding to *key* as an
172
instance of the appropriate format-specific :class:`Message` subclass, or
173
raise a :exc:`KeyError` exception if no such message exists.
176
.. method:: get_string(key)
178
Return a string representation of the message corresponding to *key*, or
179
raise a :exc:`KeyError` exception if no such message exists.
182
.. method:: get_file(key)
184
Return a file-like representation of the message corresponding to *key*,
185
or raise a :exc:`KeyError` exception if no such message exists. The
186
file-like object behaves as if open in binary mode. This file should be
187
closed once it is no longer needed.
191
Unlike other representations of messages, file-like representations are
192
not necessarily independent of the :class:`Mailbox` instance that
193
created them or of the underlying mailbox. More specific documentation
194
is provided by each subclass.
197
.. method:: has_key(key)
200
Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
203
.. method:: __len__()
205
Return a count of messages in the mailbox.
210
Delete all messages from the mailbox.
213
.. method:: pop(key[, default])
215
Return a representation of the message corresponding to *key* and delete
216
the message. If no such message exists, return *default* if it was
217
supplied or else raise a :exc:`KeyError` exception. The message is
218
represented as an instance of the appropriate format-specific
219
:class:`Message` subclass unless a custom message factory was specified
220
when the :class:`Mailbox` instance was initialized.
223
.. method:: popitem()
225
Return an arbitrary (*key*, *message*) pair, where *key* is a key and
226
*message* is a message representation, and delete the corresponding
227
message. If the mailbox is empty, raise a :exc:`KeyError` exception. The
228
message is represented as an instance of the appropriate format-specific
229
:class:`Message` subclass unless a custom message factory was specified
230
when the :class:`Mailbox` instance was initialized.
233
.. method:: update(arg)
235
Parameter *arg* should be a *key*-to-*message* mapping or an iterable of
236
(*key*, *message*) pairs. Updates the mailbox so that, for each given
237
*key* and *message*, the message corresponding to *key* is set to
238
*message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`,
239
each *key* must already correspond to a message in the mailbox or else a
240
:exc:`KeyError` exception will be raised, so in general it is incorrect
241
for *arg* to be a :class:`Mailbox` instance.
245
Unlike with dictionaries, keyword arguments are not supported.
250
Write any pending changes to the filesystem. For some :class:`Mailbox`
251
subclasses, changes are always written immediately and :meth:`flush` does
252
nothing, but you should still make a habit of calling this method.
257
Acquire an exclusive advisory lock on the mailbox so that other processes
258
know not to modify it. An :exc:`ExternalClashError` is raised if the lock
259
is not available. The particular locking mechanisms used depend upon the
260
mailbox format. You should *always* lock the mailbox before making any
261
modifications to its contents.
266
Release the lock on the mailbox, if any.
271
Flush the mailbox, unlock it if necessary, and close any open files. For
272
some :class:`Mailbox` subclasses, this method does nothing.
281
.. class:: Maildir(dirname[, factory=rfc822.Message[, create=True]])
283
A subclass of :class:`Mailbox` for mailboxes in Maildir format. Parameter
284
*factory* is a callable object that accepts a file-like message representation
285
(which behaves as if opened in binary mode) and returns a custom representation.
286
If *factory* is ``None``, :class:`MaildirMessage` is used as the default message
287
representation. If *create* is ``True``, the mailbox is created if it does not
290
It is for historical reasons that *factory* defaults to :class:`rfc822.Message`
291
and that *dirname* is named as such rather than *path*. For a :class:`Maildir`
292
instance that behaves like instances of other :class:`Mailbox` subclasses, set
293
*factory* to ``None``.
295
Maildir is a directory-based mailbox format invented for the qmail mail
296
transfer agent and now widely supported by other programs. Messages in a
297
Maildir mailbox are stored in separate files within a common directory
298
structure. This design allows Maildir mailboxes to be accessed and modified
299
by multiple unrelated programs without data corruption, so file locking is
302
Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
303
:file:`new`, and :file:`cur`. Messages are created momentarily in the
304
:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to
305
finalize delivery. A mail user agent may subsequently move the message to the
306
:file:`cur` subdirectory and store information about the state of the message
307
in a special "info" section appended to its file name.
309
Folders of the style introduced by the Courier mail transfer agent are also
310
supported. Any subdirectory of the main mailbox is considered a folder if
311
``'.'`` is the first character in its name. Folder names are represented by
312
:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
313
mailbox but should not contain other folders. Instead, a logical nesting is
314
indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
318
The Maildir specification requires the use of a colon (``':'``) in certain
319
message file names. However, some operating systems do not permit this
320
character in file names, If you wish to use a Maildir-like format on such
321
an operating system, you should specify another character to use
322
instead. The exclamation point (``'!'``) is a popular choice. For
326
mailbox.Maildir.colon = '!'
328
The :attr:`colon` attribute may also be set on a per-instance basis.
330
:class:`Maildir` instances have all of the methods of :class:`Mailbox` in
331
addition to the following:
334
.. method:: list_folders()
336
Return a list of the names of all folders.
339
.. method:: .et_folder(folder)
341
Return a :class:`Maildir` instance representing the folder whose name is
342
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
346
.. method:: add_folder(folder)
348
Create a folder whose name is *folder* and return a :class:`Maildir`
349
instance representing it.
352
.. method:: remove_folder(folder)
354
Delete the folder whose name is *folder*. If the folder contains any
355
messages, a :exc:`NotEmptyError` exception will be raised and the folder
361
Delete temporary files from the mailbox that have not been accessed in the
362
last 36 hours. The Maildir specification says that mail-reading programs
363
should do this occasionally.
365
Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
369
.. method:: add(message)
370
__setitem__(key, message)
375
These methods generate unique file names based upon the current process
376
ID. When using multiple threads, undetected name clashes may occur and
377
cause corruption of the mailbox unless threads are coordinated to avoid
378
using these methods to manipulate the same mailbox simultaneously.
383
All changes to Maildir mailboxes are immediately applied, so this method
390
Maildir mailboxes do not support (or require) locking, so these methods do
396
:class:`Maildir` instances do not keep any open files and the underlying
397
mailboxes do not support locking, so this method does nothing.
400
.. method:: get_file(key)
402
Depending upon the host platform, it may not be possible to modify or
403
remove the underlying message while the returned file remains open.
408
`maildir man page from qmail <http://www.qmail.org/man/man5/maildir.html>`_
409
The original specification of the format.
411
`Using maildir format <http://cr.yp.to/proto/maildir.html>`_
412
Notes on Maildir by its inventor. Includes an updated name-creation scheme and
413
details on "info" semantics.
415
`maildir man page from Courier <http://www.courier-mta.org/maildir.html>`_
416
Another specification of the format. Describes a common extension for supporting
426
.. class:: mbox(path[, factory=None[, create=True]])
428
A subclass of :class:`Mailbox` for mailboxes in mbox format. Parameter *factory*
429
is a callable object that accepts a file-like message representation (which
430
behaves as if opened in binary mode) and returns a custom representation. If
431
*factory* is ``None``, :class:`mboxMessage` is used as the default message
432
representation. If *create* is ``True``, the mailbox is created if it does not
435
The mbox format is the classic format for storing mail on Unix systems. All
436
messages in an mbox mailbox are stored in a single file with the beginning of
437
each message indicated by a line whose first five characters are "From ".
439
Several variations of the mbox format exist to address perceived shortcomings in
440
the original. In the interest of compatibility, :class:`mbox` implements the
441
original format, which is sometimes referred to as :dfn:`mboxo`. This means that
442
the :mailheader:`Content-Length` header, if present, is ignored and that any
443
occurrences of "From " at the beginning of a line in a message body are
444
transformed to ">From " when storing the message, although occurrences of ">From
445
" are not transformed to "From " when reading the message.
447
Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
451
.. method:: get_file(key)
453
Using the file after calling :meth:`flush` or :meth:`close` on the
454
:class:`mbox` instance may yield unpredictable results or raise an
461
Three locking mechanisms are used---dot locking and, if available, the
462
:cfunc:`flock` and :cfunc:`lockf` system calls.
467
`mbox man page from qmail <http://www.qmail.org/man/man5/mbox.html>`_
468
A specification of the format and its variations.
470
`mbox man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mbox>`_
471
Another specification of the format, with details on locking.
473
`Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <http://www.jwz.org/doc/content-length.html>`_
474
An argument for using the original mbox format rather than a variation.
476
`"mbox" is a family of several mutually incompatible mailbox formats <http://homepages.tesco.net./~J.deBoynePollard/FGA/mail-mbox-formats.html>`_
477
A history of mbox variations.
486
.. class:: MH(path[, factory=None[, create=True]])
488
A subclass of :class:`Mailbox` for mailboxes in MH format. Parameter *factory*
489
is a callable object that accepts a file-like message representation (which
490
behaves as if opened in binary mode) and returns a custom representation. If
491
*factory* is ``None``, :class:`MHMessage` is used as the default message
492
representation. If *create* is ``True``, the mailbox is created if it does not
495
MH is a directory-based mailbox format invented for the MH Message Handling
496
System, a mail user agent. Each message in an MH mailbox resides in its own
497
file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in
498
addition to messages. Folders may be nested indefinitely. MH mailboxes also
499
support :dfn:`sequences`, which are named lists used to logically group
500
messages without moving them to sub-folders. Sequences are defined in a file
501
called :file:`.mh_sequences` in each folder.
503
The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
504
emulate all of :program:`mh`'s behaviors. In particular, it does not modify
505
and is not affected by the :file:`context` or :file:`.mh_profile` files that
506
are used by :program:`mh` to store its state and configuration.
508
:class:`MH` instances have all of the methods of :class:`Mailbox` in addition
512
.. method:: list_folders()
514
Return a list of the names of all folders.
517
.. method:: get_folder(folder)
519
Return an :class:`MH` instance representing the folder whose name is
520
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
524
.. method:: add_folder(folder)
526
Create a folder whose name is *folder* and return an :class:`MH` instance
530
.. method:: remove_folder(folder)
532
Delete the folder whose name is *folder*. If the folder contains any
533
messages, a :exc:`NotEmptyError` exception will be raised and the folder
537
.. method:: get_sequences()
539
Return a dictionary of sequence names mapped to key lists. If there are no
540
sequences, the empty dictionary is returned.
543
.. method:: set_sequences(sequences)
545
Re-define the sequences that exist in the mailbox based upon *sequences*,
546
a dictionary of names mapped to key lists, like returned by
547
:meth:`get_sequences`.
552
Rename messages in the mailbox as necessary to eliminate gaps in
553
numbering. Entries in the sequences list are updated correspondingly.
557
Already-issued keys are invalidated by this operation and should not be
560
Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
564
.. method:: remove(key)
568
These methods immediately delete the message. The MH convention of marking
569
a message for deletion by prepending a comma to its name is not used.
575
Three locking mechanisms are used---dot locking and, if available, the
576
:cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking
577
the mailbox means locking the :file:`.mh_sequences` file and, only for the
578
duration of any operations that affect them, locking individual message
582
.. method:: get_file(key)
584
Depending upon the host platform, it may not be possible to remove the
585
underlying message while the returned file remains open.
590
All changes to MH mailboxes are immediately applied, so this method does
596
:class:`MH` instances do not keep any open files, so this method is
597
equivalent to :meth:`unlock`.
602
`nmh - Message Handling System <http://www.nongnu.org/nmh/>`_
603
Home page of :program:`nmh`, an updated version of the original :program:`mh`.
605
`MH & nmh: Email for Users & Programmers <http://www.ics.uci.edu/~mh/book/>`_
606
A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information
607
on the mailbox format.
616
.. class:: Babyl(path[, factory=None[, create=True]])
618
A subclass of :class:`Mailbox` for mailboxes in Babyl format. Parameter
619
*factory* is a callable object that accepts a file-like message representation
620
(which behaves as if opened in binary mode) and returns a custom representation.
621
If *factory* is ``None``, :class:`BabylMessage` is used as the default message
622
representation. If *create* is ``True``, the mailbox is created if it does not
625
Babyl is a single-file mailbox format used by the Rmail mail user agent
626
included with Emacs. The beginning of a message is indicated by a line
627
containing the two characters Control-Underscore (``'\037'``) and Control-L
628
(``'\014'``). The end of a message is indicated by the start of the next
629
message or, in the case of the last message, a line containing a
630
Control-Underscore (``'\037'``) character.
632
Messages in a Babyl mailbox have two sets of headers, original headers and
633
so-called visible headers. Visible headers are typically a subset of the
634
original headers that have been reformatted or abridged to be more
635
attractive. Each message in a Babyl mailbox also has an accompanying list of
636
:dfn:`labels`, or short strings that record extra information about the
637
message, and a list of all user-defined labels found in the mailbox is kept
638
in the Babyl options section.
640
:class:`Babyl` instances have all of the methods of :class:`Mailbox` in
641
addition to the following:
644
.. method:: get_labels()
646
Return a list of the names of all user-defined labels used in the mailbox.
650
The actual messages are inspected to determine which labels exist in
651
the mailbox rather than consulting the list of labels in the Babyl
652
options section, but the Babyl section is updated whenever the mailbox
655
Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
659
.. method:: get_file(key)
661
In Babyl mailboxes, the headers of a message are not stored contiguously
662
with the body of the message. To generate a file-like representation, the
663
headers and body are copied together into a :class:`StringIO` instance
664
(from the :mod:`StringIO` module), which has an API identical to that of a
665
file. As a result, the file-like object is truly independent of the
666
underlying mailbox but does not save memory compared to a string
673
Three locking mechanisms are used---dot locking and, if available, the
674
:cfunc:`flock` and :cfunc:`lockf` system calls.
679
`Format of Version 5 Babyl Files <http://quimby.gnus.org/notes/BABYL>`_
680
A specification of the Babyl format.
682
`Reading Mail with Rmail <http://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html>`_
683
The Rmail manual, with some information on Babyl semantics.
692
.. class:: MMDF(path[, factory=None[, create=True]])
694
A subclass of :class:`Mailbox` for mailboxes in MMDF format. Parameter *factory*
695
is a callable object that accepts a file-like message representation (which
696
behaves as if opened in binary mode) and returns a custom representation. If
697
*factory* is ``None``, :class:`MMDFMessage` is used as the default message
698
representation. If *create* is ``True``, the mailbox is created if it does not
701
MMDF is a single-file mailbox format invented for the Multichannel Memorandum
702
Distribution Facility, a mail transfer agent. Each message is in the same
703
form as an mbox message but is bracketed before and after by lines containing
704
four Control-A (``'\001'``) characters. As with the mbox format, the
705
beginning of each message is indicated by a line whose first five characters
706
are "From ", but additional occurrences of "From " are not transformed to
707
">From " when storing messages because the extra message separator lines
708
prevent mistaking such occurrences for the starts of subsequent messages.
710
Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
714
.. method:: get_file(key)
716
Using the file after calling :meth:`flush` or :meth:`close` on the
717
:class:`MMDF` instance may yield unpredictable results or raise an
724
Three locking mechanisms are used---dot locking and, if available, the
725
:cfunc:`flock` and :cfunc:`lockf` system calls.
730
`mmdf man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mmdf>`_
731
A specification of MMDF format from the documentation of tin, a newsreader.
733
`MMDF <http://en.wikipedia.org/wiki/MMDF>`_
734
A Wikipedia article describing the Multichannel Memorandum Distribution
738
.. _mailbox-message-objects:
740
:class:`Message` objects
741
------------------------
744
.. class:: Message([message])
746
A subclass of the :mod:`email.Message` module's :class:`Message`. Subclasses of
747
:class:`mailbox.Message` add mailbox-format-specific state and behavior.
749
If *message* is omitted, the new instance is created in a default, empty state.
750
If *message* is an :class:`email.Message.Message` instance, its contents are
751
copied; furthermore, any format-specific information is converted insofar as
752
possible if *message* is a :class:`Message` instance. If *message* is a string
753
or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
756
The format-specific state and behaviors offered by subclasses vary, but in
757
general it is only the properties that are not specific to a particular
758
mailbox that are supported (although presumably the properties are specific
759
to a particular mailbox format). For example, file offsets for single-file
760
mailbox formats and file names for directory-based mailbox formats are not
761
retained, because they are only applicable to the original mailbox. But state
762
such as whether a message has been read by the user or marked as important is
763
retained, because it applies to the message itself.
765
There is no requirement that :class:`Message` instances be used to represent
766
messages retrieved using :class:`Mailbox` instances. In some situations, the
767
time and memory required to generate :class:`Message` representations might
768
not not acceptable. For such situations, :class:`Mailbox` instances also
769
offer string and file-like representations, and a custom message factory may
770
be specified when a :class:`Mailbox` instance is initialized.
773
.. _mailbox-maildirmessage:
775
:class:`MaildirMessage`
776
^^^^^^^^^^^^^^^^^^^^^^^
779
.. class:: MaildirMessage([message])
781
A message with Maildir-specific behaviors. Parameter *message* has the same
782
meaning as with the :class:`Message` constructor.
784
Typically, a mail user agent application moves all of the messages in the
785
:file:`new` subdirectory to the :file:`cur` subdirectory after the first time
786
the user opens and closes the mailbox, recording that the messages are old
787
whether or not they've actually been read. Each message in :file:`cur` has an
788
"info" section added to its file name to store information about its state.
789
(Some mail readers may also add an "info" section to messages in
790
:file:`new`.) The "info" section may take one of two forms: it may contain
791
"2," followed by a list of standardized flags (e.g., "2,FR") or it may
792
contain "1," followed by so-called experimental information. Standard flags
793
for Maildir messages are as follows:
795
+------+---------+--------------------------------+
796
| Flag | Meaning | Explanation |
797
+======+=========+================================+
798
| D | Draft | Under composition |
799
+------+---------+--------------------------------+
800
| F | Flagged | Marked as important |
801
+------+---------+--------------------------------+
802
| P | Passed | Forwarded, resent, or bounced |
803
+------+---------+--------------------------------+
804
| R | Replied | Replied to |
805
+------+---------+--------------------------------+
807
+------+---------+--------------------------------+
808
| T | Trashed | Marked for subsequent deletion |
809
+------+---------+--------------------------------+
811
:class:`MaildirMessage` instances offer the following methods:
814
.. method:: get_subdir()
816
Return either "new" (if the message should be stored in the :file:`new`
817
subdirectory) or "cur" (if the message should be stored in the :file:`cur`
822
A message is typically moved from :file:`new` to :file:`cur` after its
823
mailbox has been accessed, whether or not the message is has been
824
read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is
828
.. method:: set_subdir(subdir)
830
Set the subdirectory the message should be stored in. Parameter *subdir*
831
must be either "new" or "cur".
834
.. method:: get_flags()
836
Return a string specifying the flags that are currently set. If the
837
message complies with the standard Maildir format, the result is the
838
concatenation in alphabetical order of zero or one occurrence of each of
839
``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string
840
is returned if no flags are set or if "info" contains experimental
844
.. method:: set_flags(flags)
846
Set the flags specified by *flags* and unset all others.
849
.. method:: add_flag(flag)
851
Set the flag(s) specified by *flag* without changing other flags. To add
852
more than one flag at a time, *flag* may be a string of more than one
853
character. The current "info" is overwritten whether or not it contains
854
experimental information rather than flags.
857
.. method:: remove_flag(flag)
859
Unset the flag(s) specified by *flag* without changing other flags. To
860
remove more than one flag at a time, *flag* maybe a string of more than
861
one character. If "info" contains experimental information rather than
862
flags, the current "info" is not modified.
865
.. method:: get_date()
867
Return the delivery date of the message as a floating-point number
868
representing seconds since the epoch.
871
.. method:: set_date(date)
873
Set the delivery date of the message to *date*, a floating-point number
874
representing seconds since the epoch.
877
.. method:: get_info()
879
Return a string containing the "info" for a message. This is useful for
880
accessing and modifying "info" that is experimental (i.e., not a list of
884
.. method:: set_info(info)
886
Set "info" to *info*, which should be a string.
888
When a :class:`MaildirMessage` instance is created based upon an
889
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
890
and :mailheader:`X-Status` headers are omitted and the following conversions
893
+--------------------+----------------------------------------------+
894
| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
896
+====================+==============================================+
897
| "cur" subdirectory | O flag |
898
+--------------------+----------------------------------------------+
900
+--------------------+----------------------------------------------+
902
+--------------------+----------------------------------------------+
904
+--------------------+----------------------------------------------+
906
+--------------------+----------------------------------------------+
908
When a :class:`MaildirMessage` instance is created based upon an
909
:class:`MHMessage` instance, the following conversions take place:
911
+-------------------------------+--------------------------+
912
| Resulting state | :class:`MHMessage` state |
913
+===============================+==========================+
914
| "cur" subdirectory | "unseen" sequence |
915
+-------------------------------+--------------------------+
916
| "cur" subdirectory and S flag | no "unseen" sequence |
917
+-------------------------------+--------------------------+
918
| F flag | "flagged" sequence |
919
+-------------------------------+--------------------------+
920
| R flag | "replied" sequence |
921
+-------------------------------+--------------------------+
923
When a :class:`MaildirMessage` instance is created based upon a
924
:class:`BabylMessage` instance, the following conversions take place:
926
+-------------------------------+-------------------------------+
927
| Resulting state | :class:`BabylMessage` state |
928
+===============================+===============================+
929
| "cur" subdirectory | "unseen" label |
930
+-------------------------------+-------------------------------+
931
| "cur" subdirectory and S flag | no "unseen" label |
932
+-------------------------------+-------------------------------+
933
| P flag | "forwarded" or "resent" label |
934
+-------------------------------+-------------------------------+
935
| R flag | "answered" label |
936
+-------------------------------+-------------------------------+
937
| T flag | "deleted" label |
938
+-------------------------------+-------------------------------+
941
.. _mailbox-mboxmessage:
947
.. class:: mboxMessage([message])
949
A message with mbox-specific behaviors. Parameter *message* has the same meaning
950
as with the :class:`Message` constructor.
952
Messages in an mbox mailbox are stored together in a single file. The
953
sender's envelope address and the time of delivery are typically stored in a
954
line beginning with "From " that is used to indicate the start of a message,
955
though there is considerable variation in the exact format of this data among
956
mbox implementations. Flags that indicate the state of the message, such as
957
whether it has been read or marked as important, are typically stored in
958
:mailheader:`Status` and :mailheader:`X-Status` headers.
960
Conventional flags for mbox messages are as follows:
962
+------+----------+--------------------------------+
963
| Flag | Meaning | Explanation |
964
+======+==========+================================+
966
+------+----------+--------------------------------+
967
| O | Old | Previously detected by MUA |
968
+------+----------+--------------------------------+
969
| D | Deleted | Marked for subsequent deletion |
970
+------+----------+--------------------------------+
971
| F | Flagged | Marked as important |
972
+------+----------+--------------------------------+
973
| A | Answered | Replied to |
974
+------+----------+--------------------------------+
976
The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
977
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
978
flags and headers typically appear in the order mentioned.
980
:class:`mboxMessage` instances offer the following methods:
983
.. method:: get_from()
985
Return a string representing the "From " line that marks the start of the
986
message in an mbox mailbox. The leading "From " and the trailing newline
990
.. method:: set_from(from_[, time_=None])
992
Set the "From " line to *from_*, which should be specified without a
993
leading "From " or trailing newline. For convenience, *time_* may be
994
specified and will be formatted appropriately and appended to *from_*. If
995
*time_* is specified, it should be a :class:`struct_time` instance, a
996
tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
997
:meth:`time.gmtime`).
1000
.. method:: get_flags()
1002
Return a string specifying the flags that are currently set. If the
1003
message complies with the conventional format, the result is the
1004
concatenation in the following order of zero or one occurrence of each of
1005
``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1008
.. method:: set_flags(flags)
1010
Set the flags specified by *flags* and unset all others. Parameter *flags*
1011
should be the concatenation in any order of zero or more occurrences of
1012
each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1015
.. method:: add_flag(flag)
1017
Set the flag(s) specified by *flag* without changing other flags. To add
1018
more than one flag at a time, *flag* may be a string of more than one
1022
.. method:: remove_flag(flag)
1024
Unset the flag(s) specified by *flag* without changing other flags. To
1025
remove more than one flag at a time, *flag* maybe a string of more than
1028
When an :class:`mboxMessage` instance is created based upon a
1029
:class:`MaildirMessage` instance, a "From " line is generated based upon the
1030
:class:`MaildirMessage` instance's delivery date, and the following conversions
1033
+-----------------+-------------------------------+
1034
| Resulting state | :class:`MaildirMessage` state |
1035
+=================+===============================+
1037
+-----------------+-------------------------------+
1038
| O flag | "cur" subdirectory |
1039
+-----------------+-------------------------------+
1041
+-----------------+-------------------------------+
1043
+-----------------+-------------------------------+
1045
+-----------------+-------------------------------+
1047
When an :class:`mboxMessage` instance is created based upon an
1048
:class:`MHMessage` instance, the following conversions take place:
1050
+-------------------+--------------------------+
1051
| Resulting state | :class:`MHMessage` state |
1052
+===================+==========================+
1053
| R flag and O flag | no "unseen" sequence |
1054
+-------------------+--------------------------+
1055
| O flag | "unseen" sequence |
1056
+-------------------+--------------------------+
1057
| F flag | "flagged" sequence |
1058
+-------------------+--------------------------+
1059
| A flag | "replied" sequence |
1060
+-------------------+--------------------------+
1062
When an :class:`mboxMessage` instance is created based upon a
1063
:class:`BabylMessage` instance, the following conversions take place:
1065
+-------------------+-----------------------------+
1066
| Resulting state | :class:`BabylMessage` state |
1067
+===================+=============================+
1068
| R flag and O flag | no "unseen" label |
1069
+-------------------+-----------------------------+
1070
| O flag | "unseen" label |
1071
+-------------------+-----------------------------+
1072
| D flag | "deleted" label |
1073
+-------------------+-----------------------------+
1074
| A flag | "answered" label |
1075
+-------------------+-----------------------------+
1077
When a :class:`Message` instance is created based upon an :class:`MMDFMessage`
1078
instance, the "From " line is copied and all flags directly correspond:
1080
+-----------------+----------------------------+
1081
| Resulting state | :class:`MMDFMessage` state |
1082
+=================+============================+
1084
+-----------------+----------------------------+
1086
+-----------------+----------------------------+
1088
+-----------------+----------------------------+
1090
+-----------------+----------------------------+
1092
+-----------------+----------------------------+
1095
.. _mailbox-mhmessage:
1101
.. class:: MHMessage([message])
1103
A message with MH-specific behaviors. Parameter *message* has the same meaning
1104
as with the :class:`Message` constructor.
1106
MH messages do not support marks or flags in the traditional sense, but they
1107
do support sequences, which are logical groupings of arbitrary messages. Some
1108
mail reading programs (although not the standard :program:`mh` and
1109
:program:`nmh`) use sequences in much the same way flags are used with other
1110
formats, as follows:
1112
+----------+------------------------------------------+
1113
| Sequence | Explanation |
1114
+==========+==========================================+
1115
| unseen | Not read, but previously detected by MUA |
1116
+----------+------------------------------------------+
1117
| replied | Replied to |
1118
+----------+------------------------------------------+
1119
| flagged | Marked as important |
1120
+----------+------------------------------------------+
1122
:class:`MHMessage` instances offer the following methods:
1125
.. method:: get_sequences()
1127
Return a list of the names of sequences that include this message.
1130
.. method:: set_sequences(sequences)
1132
Set the list of sequences that include this message.
1135
.. method:: add_sequence(sequence)
1137
Add *sequence* to the list of sequences that include this message.
1140
.. method:: remove_sequence(sequence)
1142
Remove *sequence* from the list of sequences that include this message.
1144
When an :class:`MHMessage` instance is created based upon a
1145
:class:`MaildirMessage` instance, the following conversions take place:
1147
+--------------------+-------------------------------+
1148
| Resulting state | :class:`MaildirMessage` state |
1149
+====================+===============================+
1150
| "unseen" sequence | no S flag |
1151
+--------------------+-------------------------------+
1152
| "replied" sequence | R flag |
1153
+--------------------+-------------------------------+
1154
| "flagged" sequence | F flag |
1155
+--------------------+-------------------------------+
1157
When an :class:`MHMessage` instance is created based upon an
1158
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1159
and :mailheader:`X-Status` headers are omitted and the following conversions
1162
+--------------------+----------------------------------------------+
1163
| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1165
+====================+==============================================+
1166
| "unseen" sequence | no R flag |
1167
+--------------------+----------------------------------------------+
1168
| "replied" sequence | A flag |
1169
+--------------------+----------------------------------------------+
1170
| "flagged" sequence | F flag |
1171
+--------------------+----------------------------------------------+
1173
When an :class:`MHMessage` instance is created based upon a
1174
:class:`BabylMessage` instance, the following conversions take place:
1176
+--------------------+-----------------------------+
1177
| Resulting state | :class:`BabylMessage` state |
1178
+====================+=============================+
1179
| "unseen" sequence | "unseen" label |
1180
+--------------------+-----------------------------+
1181
| "replied" sequence | "answered" label |
1182
+--------------------+-----------------------------+
1185
.. _mailbox-babylmessage:
1187
:class:`BabylMessage`
1188
^^^^^^^^^^^^^^^^^^^^^
1191
.. class:: BabylMessage([message])
1193
A message with Babyl-specific behaviors. Parameter *message* has the same
1194
meaning as with the :class:`Message` constructor.
1196
Certain message labels, called :dfn:`attributes`, are defined by convention
1197
to have special meanings. The attributes are as follows:
1199
+-----------+------------------------------------------+
1200
| Label | Explanation |
1201
+===========+==========================================+
1202
| unseen | Not read, but previously detected by MUA |
1203
+-----------+------------------------------------------+
1204
| deleted | Marked for subsequent deletion |
1205
+-----------+------------------------------------------+
1206
| filed | Copied to another file or mailbox |
1207
+-----------+------------------------------------------+
1208
| answered | Replied to |
1209
+-----------+------------------------------------------+
1210
| forwarded | Forwarded |
1211
+-----------+------------------------------------------+
1212
| edited | Modified by the user |
1213
+-----------+------------------------------------------+
1215
+-----------+------------------------------------------+
1217
By default, Rmail displays only visible headers. The :class:`BabylMessage`
1218
class, though, uses the original headers because they are more
1219
complete. Visible headers may be accessed explicitly if desired.
1221
:class:`BabylMessage` instances offer the following methods:
1224
.. method:: get_labels()
1226
Return a list of labels on the message.
1229
.. method:: set_labels(labels)
1231
Set the list of labels on the message to *labels*.
1234
.. method:: add_label(label)
1236
Add *label* to the list of labels on the message.
1239
.. method:: remove_label(label)
1241
Remove *label* from the list of labels on the message.
1244
.. method:: get_visible()
1246
Return an :class:`Message` instance whose headers are the message's
1247
visible headers and whose body is empty.
1250
.. method:: set_visible(visible)
1252
Set the message's visible headers to be the same as the headers in
1253
*message*. Parameter *visible* should be a :class:`Message` instance, an
1254
:class:`email.Message.Message` instance, a string, or a file-like object
1255
(which should be open in text mode).
1258
.. method:: update_visible()
1260
When a :class:`BabylMessage` instance's original headers are modified, the
1261
visible headers are not automatically modified to correspond. This method
1262
updates the visible headers as follows: each visible header with a
1263
corresponding original header is set to the value of the original header,
1264
each visible header without a corresponding original header is removed,
1265
and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`,
1266
:mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are
1267
present in the original headers but not the visible headers are added to
1268
the visible headers.
1270
When a :class:`BabylMessage` instance is created based upon a
1271
:class:`MaildirMessage` instance, the following conversions take place:
1273
+-------------------+-------------------------------+
1274
| Resulting state | :class:`MaildirMessage` state |
1275
+===================+===============================+
1276
| "unseen" label | no S flag |
1277
+-------------------+-------------------------------+
1278
| "deleted" label | T flag |
1279
+-------------------+-------------------------------+
1280
| "answered" label | R flag |
1281
+-------------------+-------------------------------+
1282
| "forwarded" label | P flag |
1283
+-------------------+-------------------------------+
1285
When a :class:`BabylMessage` instance is created based upon an
1286
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1287
and :mailheader:`X-Status` headers are omitted and the following conversions
1290
+------------------+----------------------------------------------+
1291
| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1293
+==================+==============================================+
1294
| "unseen" label | no R flag |
1295
+------------------+----------------------------------------------+
1296
| "deleted" label | D flag |
1297
+------------------+----------------------------------------------+
1298
| "answered" label | A flag |
1299
+------------------+----------------------------------------------+
1301
When a :class:`BabylMessage` instance is created based upon an
1302
:class:`MHMessage` instance, the following conversions take place:
1304
+------------------+--------------------------+
1305
| Resulting state | :class:`MHMessage` state |
1306
+==================+==========================+
1307
| "unseen" label | "unseen" sequence |
1308
+------------------+--------------------------+
1309
| "answered" label | "replied" sequence |
1310
+------------------+--------------------------+
1313
.. _mailbox-mmdfmessage:
1315
:class:`MMDFMessage`
1316
^^^^^^^^^^^^^^^^^^^^
1319
.. class:: MMDFMessage([message])
1321
A message with MMDF-specific behaviors. Parameter *message* has the same meaning
1322
as with the :class:`Message` constructor.
1324
As with message in an mbox mailbox, MMDF messages are stored with the
1325
sender's address and the delivery date in an initial line beginning with
1326
"From ". Likewise, flags that indicate the state of the message are
1327
typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers.
1329
Conventional flags for MMDF messages are identical to those of mbox message
1332
+------+----------+--------------------------------+
1333
| Flag | Meaning | Explanation |
1334
+======+==========+================================+
1336
+------+----------+--------------------------------+
1337
| O | Old | Previously detected by MUA |
1338
+------+----------+--------------------------------+
1339
| D | Deleted | Marked for subsequent deletion |
1340
+------+----------+--------------------------------+
1341
| F | Flagged | Marked as important |
1342
+------+----------+--------------------------------+
1343
| A | Answered | Replied to |
1344
+------+----------+--------------------------------+
1346
The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
1347
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
1348
flags and headers typically appear in the order mentioned.
1350
:class:`MMDFMessage` instances offer the following methods, which are
1351
identical to those offered by :class:`mboxMessage`:
1354
.. method:: get_from()
1356
Return a string representing the "From " line that marks the start of the
1357
message in an mbox mailbox. The leading "From " and the trailing newline
1361
.. method:: set_from(from_[, time_=None])
1363
Set the "From " line to *from_*, which should be specified without a
1364
leading "From " or trailing newline. For convenience, *time_* may be
1365
specified and will be formatted appropriately and appended to *from_*. If
1366
*time_* is specified, it should be a :class:`struct_time` instance, a
1367
tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
1368
:meth:`time.gmtime`).
1371
.. method:: get_flags()
1373
Return a string specifying the flags that are currently set. If the
1374
message complies with the conventional format, the result is the
1375
concatenation in the following order of zero or one occurrence of each of
1376
``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1379
.. method:: set_flags(flags)
1381
Set the flags specified by *flags* and unset all others. Parameter *flags*
1382
should be the concatenation in any order of zero or more occurrences of
1383
each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1386
.. method:: add_flag(flag)
1388
Set the flag(s) specified by *flag* without changing other flags. To add
1389
more than one flag at a time, *flag* may be a string of more than one
1393
.. method:: remove_flag(flag)
1395
Unset the flag(s) specified by *flag* without changing other flags. To
1396
remove more than one flag at a time, *flag* maybe a string of more than
1399
When an :class:`MMDFMessage` instance is created based upon a
1400
:class:`MaildirMessage` instance, a "From " line is generated based upon the
1401
:class:`MaildirMessage` instance's delivery date, and the following conversions
1404
+-----------------+-------------------------------+
1405
| Resulting state | :class:`MaildirMessage` state |
1406
+=================+===============================+
1408
+-----------------+-------------------------------+
1409
| O flag | "cur" subdirectory |
1410
+-----------------+-------------------------------+
1412
+-----------------+-------------------------------+
1414
+-----------------+-------------------------------+
1416
+-----------------+-------------------------------+
1418
When an :class:`MMDFMessage` instance is created based upon an
1419
:class:`MHMessage` instance, the following conversions take place:
1421
+-------------------+--------------------------+
1422
| Resulting state | :class:`MHMessage` state |
1423
+===================+==========================+
1424
| R flag and O flag | no "unseen" sequence |
1425
+-------------------+--------------------------+
1426
| O flag | "unseen" sequence |
1427
+-------------------+--------------------------+
1428
| F flag | "flagged" sequence |
1429
+-------------------+--------------------------+
1430
| A flag | "replied" sequence |
1431
+-------------------+--------------------------+
1433
When an :class:`MMDFMessage` instance is created based upon a
1434
:class:`BabylMessage` instance, the following conversions take place:
1436
+-------------------+-----------------------------+
1437
| Resulting state | :class:`BabylMessage` state |
1438
+===================+=============================+
1439
| R flag and O flag | no "unseen" label |
1440
+-------------------+-----------------------------+
1441
| O flag | "unseen" label |
1442
+-------------------+-----------------------------+
1443
| D flag | "deleted" label |
1444
+-------------------+-----------------------------+
1445
| A flag | "answered" label |
1446
+-------------------+-----------------------------+
1448
When an :class:`MMDFMessage` instance is created based upon an
1449
:class:`mboxMessage` instance, the "From " line is copied and all flags directly
1452
+-----------------+----------------------------+
1453
| Resulting state | :class:`mboxMessage` state |
1454
+=================+============================+
1456
+-----------------+----------------------------+
1458
+-----------------+----------------------------+
1460
+-----------------+----------------------------+
1462
+-----------------+----------------------------+
1464
+-----------------+----------------------------+
1470
The following exception classes are defined in the :mod:`mailbox` module:
1473
.. exception:: Error()
1475
The based class for all other module-specific exceptions.
1478
.. exception:: NoSuchMailboxError()
1480
Raised when a mailbox is expected but is not found, such as when instantiating a
1481
:class:`Mailbox` subclass with a path that does not exist (and with the *create*
1482
parameter set to ``False``), or when opening a folder that does not exist.
1485
.. exception:: NotEmptyError()
1487
Raised when a mailbox is not empty but is expected to be, such as when deleting
1488
a folder that contains messages.
1491
.. exception:: ExternalClashError()
1493
Raised when some mailbox-related condition beyond the control of the program
1494
causes it to be unable to proceed, such as when failing to acquire a lock that
1495
another program already holds a lock, or when a uniquely-generated file name
1499
.. exception:: FormatError()
1501
Raised when the data in a file cannot be parsed, such as when an :class:`MH`
1502
instance attempts to read a corrupted :file:`.mh_sequences` file.
1505
.. _mailbox-deprecated:
1507
Deprecated classes and methods
1508
------------------------------
1512
Older versions of the :mod:`mailbox` module do not support modification of
1513
mailboxes, such as adding or removing message, and do not provide classes to
1514
represent format-specific message properties. For backward compatibility, the
1515
older mailbox classes are still available, but the newer classes should be used
1516
in preference to them. The old classes will be removed in Python 3.0.
1518
Older mailbox objects support only iteration and provide a single public method:
1521
.. method:: oldmailbox.next()
1523
Return the next message in the mailbox, created with the optional *factory*
1524
argument passed into the mailbox object's constructor. By default this is an
1525
:class:`rfc822.Message` object (see the :mod:`rfc822` module). Depending on the
1526
mailbox implementation the *fp* attribute of this object may be a true file
1527
object or a class instance simulating a file object, taking care of things like
1528
message boundaries if multiple mail messages are contained in a single file,
1529
etc. If no more messages are available, this method returns ``None``.
1531
Most of the older mailbox classes have names that differ from the current
1532
mailbox class names, except for :class:`Maildir`. For this reason, the new
1533
:class:`Maildir` class defines a :meth:`next` method and its constructor differs
1534
slightly from those of the other new mailbox classes.
1536
The older mailbox classes whose names are not the same as their newer
1537
counterparts are as follows:
1540
.. class:: UnixMailbox(fp[, factory])
1542
Access to a classic Unix-style mailbox, where all messages are contained in a
1543
single file and separated by ``From`` (a.k.a. ``From_``) lines. The file object
1544
*fp* points to the mailbox file. The optional *factory* parameter is a callable
1545
that should create new message objects. *factory* is called with one argument,
1546
*fp* by the :meth:`next` method of the mailbox object. The default is the
1547
:class:`rfc822.Message` class (see the :mod:`rfc822` module -- and the note
1552
For reasons of this module's internal implementation, you will probably want to
1553
open the *fp* object in binary mode. This is especially important on Windows.
1555
For maximum portability, messages in a Unix-style mailbox are separated by any
1556
line that begins exactly with the string ``'From '`` (note the trailing space)
1557
if preceded by exactly two newlines. Because of the wide-range of variations in
1558
practice, nothing else on the ``From_`` line should be considered. However, the
1559
current implementation doesn't check for the leading two newlines. This is
1560
usually fine for most applications.
1562
The :class:`UnixMailbox` class implements a more strict version of ``From_``
1563
line checking, using a regular expression that usually correctly matched
1564
``From_`` delimiters. It considers delimiter line to be separated by ``From
1565
name time`` lines. For maximum portability, use the
1566
:class:`PortableUnixMailbox` class instead. This class is identical to
1567
:class:`UnixMailbox` except that individual messages are separated by only
1571
.. class:: PortableUnixMailbox(fp[, factory])
1573
A less-strict version of :class:`UnixMailbox`, which considers only the ``From``
1574
at the beginning of the line separating messages. The "*name* *time*" portion
1575
of the From line is ignored, to protect against some variations that are
1576
observed in practice. This works since lines in the message which begin with
1577
``'From '`` are quoted by mail handling software at delivery-time.
1580
.. class:: MmdfMailbox(fp[, factory])
1582
Access an MMDF-style mailbox, where all messages are contained in a single file
1583
and separated by lines consisting of 4 control-A characters. The file object
1584
*fp* points to the mailbox file. Optional *factory* is as with the
1585
:class:`UnixMailbox` class.
1588
.. class:: MHMailbox(dirname[, factory])
1590
Access an MH mailbox, a directory with each message in a separate file with a
1591
numeric name. The name of the mailbox directory is passed in *dirname*.
1592
*factory* is as with the :class:`UnixMailbox` class.
1595
.. class:: BabylMailbox(fp[, factory])
1597
Access a Babyl mailbox, which is similar to an MMDF mailbox. In Babyl format,
1598
each message has two sets of headers, the *original* headers and the *visible*
1599
headers. The original headers appear before a line containing only ``'*** EOOH
1600
***'`` (End-Of-Original-Headers) and the visible headers appear after the
1601
``EOOH`` line. Babyl-compliant mail readers will show you only the visible
1602
headers, and :class:`BabylMailbox` objects will return messages containing only
1603
the visible headers. You'll have to do your own parsing of the mailbox file to
1604
get at the original headers. Mail messages start with the EOOH line and end
1605
with a line containing only ``'\037\014'``. *factory* is as with the
1606
:class:`UnixMailbox` class.
1608
If you wish to use the older mailbox classes with the :mod:`email` module rather
1609
than the deprecated :mod:`rfc822` module, you can do so as follows::
1617
return email.message_from_file(fp)
1618
except email.Errors.MessageParseError:
1619
# Don't return None since that will
1620
# stop the mailbox iterator
1623
mbox = mailbox.UnixMailbox(fp, msgfactory)
1625
Alternatively, if you know your mailbox contains only well-formed MIME messages,
1626
you can simplify this to::
1631
mbox = mailbox.UnixMailbox(fp, email.message_from_file)
1634
.. _mailbox-examples:
1639
A simple example of printing the subjects of all messages in a mailbox that seem
1643
for message in mailbox.mbox('~/mbox'):
1644
subject = message['subject'] # Could possibly be None.
1645
if subject and 'python' in subject.lower():
1648
To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
1649
format-specific information that can be converted::
1652
destination = mailbox.MH('~/Mail')
1654
for message in mailbox.Babyl('~/RMAIL'):
1655
destination.add(mailbox.MHMessage(message))
1657
destination.unlock()
1659
This example sorts mail from several mailing lists into different mailboxes,
1660
being careful to avoid mail corruption due to concurrent modification by other
1661
programs, mail loss due to interruption of the program, or premature termination
1662
due to malformed messages in the mailbox::
1667
list_names = ('python-list', 'python-dev', 'python-bugs')
1669
boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names)
1670
inbox = mailbox.Maildir('~/Maildir', factory=None)
1672
for key in inbox.iterkeys():
1674
message = inbox[key]
1675
except email.Errors.MessageParseError:
1676
continue # The message is malformed. Just leave it.
1678
for name in list_names:
1679
list_id = message['list-id']
1680
if list_id and name in list_id:
1681
# Get mailbox to use
1684
# Write copy to disk before removing original.
1685
# If there's a crash, you might duplicate a message, but
1686
# that's better than losing a message completely.
1692
# Remove original message
1697
break # Found destination, so stop looking.
1699
for box in boxes.itervalues():