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:: __contains__(key)
199
Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
202
.. method:: __len__()
204
Return a count of messages in the mailbox.
209
Delete all messages from the mailbox.
212
.. method:: pop(key[, default])
214
Return a representation of the message corresponding to *key* and delete
215
the message. If no such message exists, return *default* if it was
216
supplied or else raise a :exc:`KeyError` exception. The message is
217
represented as an instance of the appropriate format-specific
218
:class:`Message` subclass unless a custom message factory was specified
219
when the :class:`Mailbox` instance was initialized.
222
.. method:: popitem()
224
Return an arbitrary (*key*, *message*) pair, where *key* is a key and
225
*message* is a message representation, and delete the corresponding
226
message. If the mailbox is empty, raise a :exc:`KeyError` exception. The
227
message is represented as an instance of the appropriate format-specific
228
:class:`Message` subclass unless a custom message factory was specified
229
when the :class:`Mailbox` instance was initialized.
232
.. method:: update(arg)
234
Parameter *arg* should be a *key*-to-*message* mapping or an iterable of
235
(*key*, *message*) pairs. Updates the mailbox so that, for each given
236
*key* and *message*, the message corresponding to *key* is set to
237
*message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`,
238
each *key* must already correspond to a message in the mailbox or else a
239
:exc:`KeyError` exception will be raised, so in general it is incorrect
240
for *arg* to be a :class:`Mailbox` instance.
244
Unlike with dictionaries, keyword arguments are not supported.
249
Write any pending changes to the filesystem. For some :class:`Mailbox`
250
subclasses, changes are always written immediately and :meth:`flush` does
251
nothing, but you should still make a habit of calling this method.
256
Acquire an exclusive advisory lock on the mailbox so that other processes
257
know not to modify it. An :exc:`ExternalClashError` is raised if the lock
258
is not available. The particular locking mechanisms used depend upon the
259
mailbox format. You should *always* lock the mailbox before making any
260
modifications to its contents.
265
Release the lock on the mailbox, if any.
270
Flush the mailbox, unlock it if necessary, and close any open files. For
271
some :class:`Mailbox` subclasses, this method does nothing.
280
.. class:: Maildir(dirname[, factory=None[, create=True]])
282
A subclass of :class:`Mailbox` for mailboxes in Maildir format. Parameter
283
*factory* is a callable object that accepts a file-like message representation
284
(which behaves as if opened in binary mode) and returns a custom representation.
285
If *factory* is ``None``, :class:`MaildirMessage` is used as the default message
286
representation. If *create* is ``True``, the mailbox is created if it does not
289
It is for historical reasons that *dirname* is named as such rather than *path*.
291
Maildir is a directory-based mailbox format invented for the qmail mail
292
transfer agent and now widely supported by other programs. Messages in a
293
Maildir mailbox are stored in separate files within a common directory
294
structure. This design allows Maildir mailboxes to be accessed and modified
295
by multiple unrelated programs without data corruption, so file locking is
298
Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
299
:file:`new`, and :file:`cur`. Messages are created momentarily in the
300
:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to
301
finalize delivery. A mail user agent may subsequently move the message to the
302
:file:`cur` subdirectory and store information about the state of the message
303
in a special "info" section appended to its file name.
305
Folders of the style introduced by the Courier mail transfer agent are also
306
supported. Any subdirectory of the main mailbox is considered a folder if
307
``'.'`` is the first character in its name. Folder names are represented by
308
:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
309
mailbox but should not contain other folders. Instead, a logical nesting is
310
indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
314
The Maildir specification requires the use of a colon (``':'``) in certain
315
message file names. However, some operating systems do not permit this
316
character in file names, If you wish to use a Maildir-like format on such
317
an operating system, you should specify another character to use
318
instead. The exclamation point (``'!'``) is a popular choice. For
322
mailbox.Maildir.colon = '!'
324
The :attr:`colon` attribute may also be set on a per-instance basis.
326
:class:`Maildir` instances have all of the methods of :class:`Mailbox` in
327
addition to the following:
330
.. method:: list_folders()
332
Return a list of the names of all folders.
335
.. method:: .et_folder(folder)
337
Return a :class:`Maildir` instance representing the folder whose name is
338
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
342
.. method:: add_folder(folder)
344
Create a folder whose name is *folder* and return a :class:`Maildir`
345
instance representing it.
348
.. method:: remove_folder(folder)
350
Delete the folder whose name is *folder*. If the folder contains any
351
messages, a :exc:`NotEmptyError` exception will be raised and the folder
357
Delete temporary files from the mailbox that have not been accessed in the
358
last 36 hours. The Maildir specification says that mail-reading programs
359
should do this occasionally.
361
Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
365
.. method:: add(message)
366
__setitem__(key, message)
371
These methods generate unique file names based upon the current process
372
ID. When using multiple threads, undetected name clashes may occur and
373
cause corruption of the mailbox unless threads are coordinated to avoid
374
using these methods to manipulate the same mailbox simultaneously.
379
All changes to Maildir mailboxes are immediately applied, so this method
386
Maildir mailboxes do not support (or require) locking, so these methods do
392
:class:`Maildir` instances do not keep any open files and the underlying
393
mailboxes do not support locking, so this method does nothing.
396
.. method:: get_file(key)
398
Depending upon the host platform, it may not be possible to modify or
399
remove the underlying message while the returned file remains open.
404
`maildir man page from qmail <http://www.qmail.org/man/man5/maildir.html>`_
405
The original specification of the format.
407
`Using maildir format <http://cr.yp.to/proto/maildir.html>`_
408
Notes on Maildir by its inventor. Includes an updated name-creation scheme and
409
details on "info" semantics.
411
`maildir man page from Courier <http://www.courier-mta.org/maildir.html>`_
412
Another specification of the format. Describes a common extension for supporting
422
.. class:: mbox(path[, factory=None[, create=True]])
424
A subclass of :class:`Mailbox` for mailboxes in mbox format. Parameter *factory*
425
is a callable object that accepts a file-like message representation (which
426
behaves as if opened in binary mode) and returns a custom representation. If
427
*factory* is ``None``, :class:`mboxMessage` is used as the default message
428
representation. If *create* is ``True``, the mailbox is created if it does not
431
The mbox format is the classic format for storing mail on Unix systems. All
432
messages in an mbox mailbox are stored in a single file with the beginning of
433
each message indicated by a line whose first five characters are "From ".
435
Several variations of the mbox format exist to address perceived shortcomings in
436
the original. In the interest of compatibility, :class:`mbox` implements the
437
original format, which is sometimes referred to as :dfn:`mboxo`. This means that
438
the :mailheader:`Content-Length` header, if present, is ignored and that any
439
occurrences of "From " at the beginning of a line in a message body are
440
transformed to ">From " when storing the message, although occurrences of ">From
441
" are not transformed to "From " when reading the message.
443
Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
447
.. method:: get_file(key)
449
Using the file after calling :meth:`flush` or :meth:`close` on the
450
:class:`mbox` instance may yield unpredictable results or raise an
457
Three locking mechanisms are used---dot locking and, if available, the
458
:cfunc:`flock` and :cfunc:`lockf` system calls.
463
`mbox man page from qmail <http://www.qmail.org/man/man5/mbox.html>`_
464
A specification of the format and its variations.
466
`mbox man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mbox>`_
467
Another specification of the format, with details on locking.
469
`Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <http://www.jwz.org/doc/content-length.html>`_
470
An argument for using the original mbox format rather than a variation.
472
`"mbox" is a family of several mutually incompatible mailbox formats <http://homepages.tesco.net./~J.deBoynePollard/FGA/mail-mbox-formats.html>`_
473
A history of mbox variations.
482
.. class:: MH(path[, factory=None[, create=True]])
484
A subclass of :class:`Mailbox` for mailboxes in MH format. Parameter *factory*
485
is a callable object that accepts a file-like message representation (which
486
behaves as if opened in binary mode) and returns a custom representation. If
487
*factory* is ``None``, :class:`MHMessage` is used as the default message
488
representation. If *create* is ``True``, the mailbox is created if it does not
491
MH is a directory-based mailbox format invented for the MH Message Handling
492
System, a mail user agent. Each message in an MH mailbox resides in its own
493
file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in
494
addition to messages. Folders may be nested indefinitely. MH mailboxes also
495
support :dfn:`sequences`, which are named lists used to logically group
496
messages without moving them to sub-folders. Sequences are defined in a file
497
called :file:`.mh_sequences` in each folder.
499
The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
500
emulate all of :program:`mh`'s behaviors. In particular, it does not modify
501
and is not affected by the :file:`context` or :file:`.mh_profile` files that
502
are used by :program:`mh` to store its state and configuration.
504
:class:`MH` instances have all of the methods of :class:`Mailbox` in addition
508
.. method:: list_folders()
510
Return a list of the names of all folders.
513
.. method:: get_folder(folder)
515
Return an :class:`MH` instance representing the folder whose name is
516
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
520
.. method:: add_folder(folder)
522
Create a folder whose name is *folder* and return an :class:`MH` instance
526
.. method:: remove_folder(folder)
528
Delete the folder whose name is *folder*. If the folder contains any
529
messages, a :exc:`NotEmptyError` exception will be raised and the folder
533
.. method:: get_sequences()
535
Return a dictionary of sequence names mapped to key lists. If there are no
536
sequences, the empty dictionary is returned.
539
.. method:: set_sequences(sequences)
541
Re-define the sequences that exist in the mailbox based upon *sequences*,
542
a dictionary of names mapped to key lists, like returned by
543
:meth:`get_sequences`.
548
Rename messages in the mailbox as necessary to eliminate gaps in
549
numbering. Entries in the sequences list are updated correspondingly.
553
Already-issued keys are invalidated by this operation and should not be
556
Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
560
.. method:: remove(key)
564
These methods immediately delete the message. The MH convention of marking
565
a message for deletion by prepending a comma to its name is not used.
571
Three locking mechanisms are used---dot locking and, if available, the
572
:cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking
573
the mailbox means locking the :file:`.mh_sequences` file and, only for the
574
duration of any operations that affect them, locking individual message
578
.. method:: get_file(key)
580
Depending upon the host platform, it may not be possible to remove the
581
underlying message while the returned file remains open.
586
All changes to MH mailboxes are immediately applied, so this method does
592
:class:`MH` instances do not keep any open files, so this method is
593
equivalent to :meth:`unlock`.
598
`nmh - Message Handling System <http://www.nongnu.org/nmh/>`_
599
Home page of :program:`nmh`, an updated version of the original :program:`mh`.
601
`MH & nmh: Email for Users & Programmers <http://www.ics.uci.edu/~mh/book/>`_
602
A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information
603
on the mailbox format.
612
.. class:: Babyl(path[, factory=None[, create=True]])
614
A subclass of :class:`Mailbox` for mailboxes in Babyl format. Parameter
615
*factory* is a callable object that accepts a file-like message representation
616
(which behaves as if opened in binary mode) and returns a custom representation.
617
If *factory* is ``None``, :class:`BabylMessage` is used as the default message
618
representation. If *create* is ``True``, the mailbox is created if it does not
621
Babyl is a single-file mailbox format used by the Rmail mail user agent
622
included with Emacs. The beginning of a message is indicated by a line
623
containing the two characters Control-Underscore (``'\037'``) and Control-L
624
(``'\014'``). The end of a message is indicated by the start of the next
625
message or, in the case of the last message, a line containing a
626
Control-Underscore (``'\037'``) character.
628
Messages in a Babyl mailbox have two sets of headers, original headers and
629
so-called visible headers. Visible headers are typically a subset of the
630
original headers that have been reformatted or abridged to be more
631
attractive. Each message in a Babyl mailbox also has an accompanying list of
632
:dfn:`labels`, or short strings that record extra information about the
633
message, and a list of all user-defined labels found in the mailbox is kept
634
in the Babyl options section.
636
:class:`Babyl` instances have all of the methods of :class:`Mailbox` in
637
addition to the following:
640
.. method:: get_labels()
642
Return a list of the names of all user-defined labels used in the mailbox.
646
The actual messages are inspected to determine which labels exist in
647
the mailbox rather than consulting the list of labels in the Babyl
648
options section, but the Babyl section is updated whenever the mailbox
651
Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
655
.. method:: get_file(key)
657
In Babyl mailboxes, the headers of a message are not stored contiguously
658
with the body of the message. To generate a file-like representation, the
659
headers and body are copied together into a :class:`StringIO` instance
660
(from the :mod:`StringIO` module), which has an API identical to that of a
661
file. As a result, the file-like object is truly independent of the
662
underlying mailbox but does not save memory compared to a string
669
Three locking mechanisms are used---dot locking and, if available, the
670
:cfunc:`flock` and :cfunc:`lockf` system calls.
675
`Format of Version 5 Babyl Files <http://quimby.gnus.org/notes/BABYL>`_
676
A specification of the Babyl format.
678
`Reading Mail with Rmail <http://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html>`_
679
The Rmail manual, with some information on Babyl semantics.
688
.. class:: MMDF(path[, factory=None[, create=True]])
690
A subclass of :class:`Mailbox` for mailboxes in MMDF format. Parameter *factory*
691
is a callable object that accepts a file-like message representation (which
692
behaves as if opened in binary mode) and returns a custom representation. If
693
*factory* is ``None``, :class:`MMDFMessage` is used as the default message
694
representation. If *create* is ``True``, the mailbox is created if it does not
697
MMDF is a single-file mailbox format invented for the Multichannel Memorandum
698
Distribution Facility, a mail transfer agent. Each message is in the same
699
form as an mbox message but is bracketed before and after by lines containing
700
four Control-A (``'\001'``) characters. As with the mbox format, the
701
beginning of each message is indicated by a line whose first five characters
702
are "From ", but additional occurrences of "From " are not transformed to
703
">From " when storing messages because the extra message separator lines
704
prevent mistaking such occurrences for the starts of subsequent messages.
706
Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
710
.. method:: get_file(key)
712
Using the file after calling :meth:`flush` or :meth:`close` on the
713
:class:`MMDF` instance may yield unpredictable results or raise an
720
Three locking mechanisms are used---dot locking and, if available, the
721
:cfunc:`flock` and :cfunc:`lockf` system calls.
726
`mmdf man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mmdf>`_
727
A specification of MMDF format from the documentation of tin, a newsreader.
729
`MMDF <http://en.wikipedia.org/wiki/MMDF>`_
730
A Wikipedia article describing the Multichannel Memorandum Distribution
734
.. _mailbox-message-objects:
736
:class:`Message` objects
737
------------------------
740
.. class:: Message([message])
742
A subclass of the :mod:`email.Message` module's :class:`Message`. Subclasses of
743
:class:`mailbox.Message` add mailbox-format-specific state and behavior.
745
If *message* is omitted, the new instance is created in a default, empty state.
746
If *message* is an :class:`email.Message.Message` instance, its contents are
747
copied; furthermore, any format-specific information is converted insofar as
748
possible if *message* is a :class:`Message` instance. If *message* is a string
749
or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
752
The format-specific state and behaviors offered by subclasses vary, but in
753
general it is only the properties that are not specific to a particular
754
mailbox that are supported (although presumably the properties are specific
755
to a particular mailbox format). For example, file offsets for single-file
756
mailbox formats and file names for directory-based mailbox formats are not
757
retained, because they are only applicable to the original mailbox. But state
758
such as whether a message has been read by the user or marked as important is
759
retained, because it applies to the message itself.
761
There is no requirement that :class:`Message` instances be used to represent
762
messages retrieved using :class:`Mailbox` instances. In some situations, the
763
time and memory required to generate :class:`Message` representations might
764
not not acceptable. For such situations, :class:`Mailbox` instances also
765
offer string and file-like representations, and a custom message factory may
766
be specified when a :class:`Mailbox` instance is initialized.
769
.. _mailbox-maildirmessage:
771
:class:`MaildirMessage`
772
^^^^^^^^^^^^^^^^^^^^^^^
775
.. class:: MaildirMessage([message])
777
A message with Maildir-specific behaviors. Parameter *message* has the same
778
meaning as with the :class:`Message` constructor.
780
Typically, a mail user agent application moves all of the messages in the
781
:file:`new` subdirectory to the :file:`cur` subdirectory after the first time
782
the user opens and closes the mailbox, recording that the messages are old
783
whether or not they've actually been read. Each message in :file:`cur` has an
784
"info" section added to its file name to store information about its state.
785
(Some mail readers may also add an "info" section to messages in
786
:file:`new`.) The "info" section may take one of two forms: it may contain
787
"2," followed by a list of standardized flags (e.g., "2,FR") or it may
788
contain "1," followed by so-called experimental information. Standard flags
789
for Maildir messages are as follows:
791
+------+---------+--------------------------------+
792
| Flag | Meaning | Explanation |
793
+======+=========+================================+
794
| D | Draft | Under composition |
795
+------+---------+--------------------------------+
796
| F | Flagged | Marked as important |
797
+------+---------+--------------------------------+
798
| P | Passed | Forwarded, resent, or bounced |
799
+------+---------+--------------------------------+
800
| R | Replied | Replied to |
801
+------+---------+--------------------------------+
803
+------+---------+--------------------------------+
804
| T | Trashed | Marked for subsequent deletion |
805
+------+---------+--------------------------------+
807
:class:`MaildirMessage` instances offer the following methods:
810
.. method:: get_subdir()
812
Return either "new" (if the message should be stored in the :file:`new`
813
subdirectory) or "cur" (if the message should be stored in the :file:`cur`
818
A message is typically moved from :file:`new` to :file:`cur` after its
819
mailbox has been accessed, whether or not the message is has been
820
read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is
824
.. method:: set_subdir(subdir)
826
Set the subdirectory the message should be stored in. Parameter *subdir*
827
must be either "new" or "cur".
830
.. method:: get_flags()
832
Return a string specifying the flags that are currently set. If the
833
message complies with the standard Maildir format, the result is the
834
concatenation in alphabetical order of zero or one occurrence of each of
835
``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string
836
is returned if no flags are set or if "info" contains experimental
840
.. method:: set_flags(flags)
842
Set the flags specified by *flags* and unset all others.
845
.. method:: add_flag(flag)
847
Set the flag(s) specified by *flag* without changing other flags. To add
848
more than one flag at a time, *flag* may be a string of more than one
849
character. The current "info" is overwritten whether or not it contains
850
experimental information rather than flags.
853
.. method:: remove_flag(flag)
855
Unset the flag(s) specified by *flag* without changing other flags. To
856
remove more than one flag at a time, *flag* maybe a string of more than
857
one character. If "info" contains experimental information rather than
858
flags, the current "info" is not modified.
861
.. method:: get_date()
863
Return the delivery date of the message as a floating-point number
864
representing seconds since the epoch.
867
.. method:: set_date(date)
869
Set the delivery date of the message to *date*, a floating-point number
870
representing seconds since the epoch.
873
.. method:: get_info()
875
Return a string containing the "info" for a message. This is useful for
876
accessing and modifying "info" that is experimental (i.e., not a list of
880
.. method:: set_info(info)
882
Set "info" to *info*, which should be a string.
884
When a :class:`MaildirMessage` instance is created based upon an
885
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
886
and :mailheader:`X-Status` headers are omitted and the following conversions
889
+--------------------+----------------------------------------------+
890
| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
892
+====================+==============================================+
893
| "cur" subdirectory | O flag |
894
+--------------------+----------------------------------------------+
896
+--------------------+----------------------------------------------+
898
+--------------------+----------------------------------------------+
900
+--------------------+----------------------------------------------+
902
+--------------------+----------------------------------------------+
904
When a :class:`MaildirMessage` instance is created based upon an
905
:class:`MHMessage` instance, the following conversions take place:
907
+-------------------------------+--------------------------+
908
| Resulting state | :class:`MHMessage` state |
909
+===============================+==========================+
910
| "cur" subdirectory | "unseen" sequence |
911
+-------------------------------+--------------------------+
912
| "cur" subdirectory and S flag | no "unseen" sequence |
913
+-------------------------------+--------------------------+
914
| F flag | "flagged" sequence |
915
+-------------------------------+--------------------------+
916
| R flag | "replied" sequence |
917
+-------------------------------+--------------------------+
919
When a :class:`MaildirMessage` instance is created based upon a
920
:class:`BabylMessage` instance, the following conversions take place:
922
+-------------------------------+-------------------------------+
923
| Resulting state | :class:`BabylMessage` state |
924
+===============================+===============================+
925
| "cur" subdirectory | "unseen" label |
926
+-------------------------------+-------------------------------+
927
| "cur" subdirectory and S flag | no "unseen" label |
928
+-------------------------------+-------------------------------+
929
| P flag | "forwarded" or "resent" label |
930
+-------------------------------+-------------------------------+
931
| R flag | "answered" label |
932
+-------------------------------+-------------------------------+
933
| T flag | "deleted" label |
934
+-------------------------------+-------------------------------+
937
.. _mailbox-mboxmessage:
943
.. class:: mboxMessage([message])
945
A message with mbox-specific behaviors. Parameter *message* has the same meaning
946
as with the :class:`Message` constructor.
948
Messages in an mbox mailbox are stored together in a single file. The
949
sender's envelope address and the time of delivery are typically stored in a
950
line beginning with "From " that is used to indicate the start of a message,
951
though there is considerable variation in the exact format of this data among
952
mbox implementations. Flags that indicate the state of the message, such as
953
whether it has been read or marked as important, are typically stored in
954
:mailheader:`Status` and :mailheader:`X-Status` headers.
956
Conventional flags for mbox messages are as follows:
958
+------+----------+--------------------------------+
959
| Flag | Meaning | Explanation |
960
+======+==========+================================+
962
+------+----------+--------------------------------+
963
| O | Old | Previously detected by MUA |
964
+------+----------+--------------------------------+
965
| D | Deleted | Marked for subsequent deletion |
966
+------+----------+--------------------------------+
967
| F | Flagged | Marked as important |
968
+------+----------+--------------------------------+
969
| A | Answered | Replied to |
970
+------+----------+--------------------------------+
972
The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
973
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
974
flags and headers typically appear in the order mentioned.
976
:class:`mboxMessage` instances offer the following methods:
979
.. method:: get_from()
981
Return a string representing the "From " line that marks the start of the
982
message in an mbox mailbox. The leading "From " and the trailing newline
986
.. method:: set_from(from_[, time_=None])
988
Set the "From " line to *from_*, which should be specified without a
989
leading "From " or trailing newline. For convenience, *time_* may be
990
specified and will be formatted appropriately and appended to *from_*. If
991
*time_* is specified, it should be a :class:`struct_time` instance, a
992
tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
993
:meth:`time.gmtime`).
996
.. method:: get_flags()
998
Return a string specifying the flags that are currently set. If the
999
message complies with the conventional format, the result is the
1000
concatenation in the following order of zero or one occurrence of each of
1001
``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1004
.. method:: set_flags(flags)
1006
Set the flags specified by *flags* and unset all others. Parameter *flags*
1007
should be the concatenation in any order of zero or more occurrences of
1008
each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1011
.. method:: add_flag(flag)
1013
Set the flag(s) specified by *flag* without changing other flags. To add
1014
more than one flag at a time, *flag* may be a string of more than one
1018
.. method:: remove_flag(flag)
1020
Unset the flag(s) specified by *flag* without changing other flags. To
1021
remove more than one flag at a time, *flag* maybe a string of more than
1024
When an :class:`mboxMessage` instance is created based upon a
1025
:class:`MaildirMessage` instance, a "From " line is generated based upon the
1026
:class:`MaildirMessage` instance's delivery date, and the following conversions
1029
+-----------------+-------------------------------+
1030
| Resulting state | :class:`MaildirMessage` state |
1031
+=================+===============================+
1033
+-----------------+-------------------------------+
1034
| O flag | "cur" subdirectory |
1035
+-----------------+-------------------------------+
1037
+-----------------+-------------------------------+
1039
+-----------------+-------------------------------+
1041
+-----------------+-------------------------------+
1043
When an :class:`mboxMessage` instance is created based upon an
1044
:class:`MHMessage` instance, the following conversions take place:
1046
+-------------------+--------------------------+
1047
| Resulting state | :class:`MHMessage` state |
1048
+===================+==========================+
1049
| R flag and O flag | no "unseen" sequence |
1050
+-------------------+--------------------------+
1051
| O flag | "unseen" sequence |
1052
+-------------------+--------------------------+
1053
| F flag | "flagged" sequence |
1054
+-------------------+--------------------------+
1055
| A flag | "replied" sequence |
1056
+-------------------+--------------------------+
1058
When an :class:`mboxMessage` instance is created based upon a
1059
:class:`BabylMessage` instance, the following conversions take place:
1061
+-------------------+-----------------------------+
1062
| Resulting state | :class:`BabylMessage` state |
1063
+===================+=============================+
1064
| R flag and O flag | no "unseen" label |
1065
+-------------------+-----------------------------+
1066
| O flag | "unseen" label |
1067
+-------------------+-----------------------------+
1068
| D flag | "deleted" label |
1069
+-------------------+-----------------------------+
1070
| A flag | "answered" label |
1071
+-------------------+-----------------------------+
1073
When a :class:`Message` instance is created based upon an :class:`MMDFMessage`
1074
instance, the "From " line is copied and all flags directly correspond:
1076
+-----------------+----------------------------+
1077
| Resulting state | :class:`MMDFMessage` state |
1078
+=================+============================+
1080
+-----------------+----------------------------+
1082
+-----------------+----------------------------+
1084
+-----------------+----------------------------+
1086
+-----------------+----------------------------+
1088
+-----------------+----------------------------+
1091
.. _mailbox-mhmessage:
1097
.. class:: MHMessage([message])
1099
A message with MH-specific behaviors. Parameter *message* has the same meaning
1100
as with the :class:`Message` constructor.
1102
MH messages do not support marks or flags in the traditional sense, but they
1103
do support sequences, which are logical groupings of arbitrary messages. Some
1104
mail reading programs (although not the standard :program:`mh` and
1105
:program:`nmh`) use sequences in much the same way flags are used with other
1106
formats, as follows:
1108
+----------+------------------------------------------+
1109
| Sequence | Explanation |
1110
+==========+==========================================+
1111
| unseen | Not read, but previously detected by MUA |
1112
+----------+------------------------------------------+
1113
| replied | Replied to |
1114
+----------+------------------------------------------+
1115
| flagged | Marked as important |
1116
+----------+------------------------------------------+
1118
:class:`MHMessage` instances offer the following methods:
1121
.. method:: get_sequences()
1123
Return a list of the names of sequences that include this message.
1126
.. method:: set_sequences(sequences)
1128
Set the list of sequences that include this message.
1131
.. method:: add_sequence(sequence)
1133
Add *sequence* to the list of sequences that include this message.
1136
.. method:: remove_sequence(sequence)
1138
Remove *sequence* from the list of sequences that include this message.
1140
When an :class:`MHMessage` instance is created based upon a
1141
:class:`MaildirMessage` instance, the following conversions take place:
1143
+--------------------+-------------------------------+
1144
| Resulting state | :class:`MaildirMessage` state |
1145
+====================+===============================+
1146
| "unseen" sequence | no S flag |
1147
+--------------------+-------------------------------+
1148
| "replied" sequence | R flag |
1149
+--------------------+-------------------------------+
1150
| "flagged" sequence | F flag |
1151
+--------------------+-------------------------------+
1153
When an :class:`MHMessage` instance is created based upon an
1154
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1155
and :mailheader:`X-Status` headers are omitted and the following conversions
1158
+--------------------+----------------------------------------------+
1159
| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1161
+====================+==============================================+
1162
| "unseen" sequence | no R flag |
1163
+--------------------+----------------------------------------------+
1164
| "replied" sequence | A flag |
1165
+--------------------+----------------------------------------------+
1166
| "flagged" sequence | F flag |
1167
+--------------------+----------------------------------------------+
1169
When an :class:`MHMessage` instance is created based upon a
1170
:class:`BabylMessage` instance, the following conversions take place:
1172
+--------------------+-----------------------------+
1173
| Resulting state | :class:`BabylMessage` state |
1174
+====================+=============================+
1175
| "unseen" sequence | "unseen" label |
1176
+--------------------+-----------------------------+
1177
| "replied" sequence | "answered" label |
1178
+--------------------+-----------------------------+
1181
.. _mailbox-babylmessage:
1183
:class:`BabylMessage`
1184
^^^^^^^^^^^^^^^^^^^^^
1187
.. class:: BabylMessage([message])
1189
A message with Babyl-specific behaviors. Parameter *message* has the same
1190
meaning as with the :class:`Message` constructor.
1192
Certain message labels, called :dfn:`attributes`, are defined by convention
1193
to have special meanings. The attributes are as follows:
1195
+-----------+------------------------------------------+
1196
| Label | Explanation |
1197
+===========+==========================================+
1198
| unseen | Not read, but previously detected by MUA |
1199
+-----------+------------------------------------------+
1200
| deleted | Marked for subsequent deletion |
1201
+-----------+------------------------------------------+
1202
| filed | Copied to another file or mailbox |
1203
+-----------+------------------------------------------+
1204
| answered | Replied to |
1205
+-----------+------------------------------------------+
1206
| forwarded | Forwarded |
1207
+-----------+------------------------------------------+
1208
| edited | Modified by the user |
1209
+-----------+------------------------------------------+
1211
+-----------+------------------------------------------+
1213
By default, Rmail displays only visible headers. The :class:`BabylMessage`
1214
class, though, uses the original headers because they are more
1215
complete. Visible headers may be accessed explicitly if desired.
1217
:class:`BabylMessage` instances offer the following methods:
1220
.. method:: get_labels()
1222
Return a list of labels on the message.
1225
.. method:: set_labels(labels)
1227
Set the list of labels on the message to *labels*.
1230
.. method:: add_label(label)
1232
Add *label* to the list of labels on the message.
1235
.. method:: remove_label(label)
1237
Remove *label* from the list of labels on the message.
1240
.. method:: get_visible()
1242
Return an :class:`Message` instance whose headers are the message's
1243
visible headers and whose body is empty.
1246
.. method:: set_visible(visible)
1248
Set the message's visible headers to be the same as the headers in
1249
*message*. Parameter *visible* should be a :class:`Message` instance, an
1250
:class:`email.Message.Message` instance, a string, or a file-like object
1251
(which should be open in text mode).
1254
.. method:: update_visible()
1256
When a :class:`BabylMessage` instance's original headers are modified, the
1257
visible headers are not automatically modified to correspond. This method
1258
updates the visible headers as follows: each visible header with a
1259
corresponding original header is set to the value of the original header,
1260
each visible header without a corresponding original header is removed,
1261
and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`,
1262
:mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are
1263
present in the original headers but not the visible headers are added to
1264
the visible headers.
1266
When a :class:`BabylMessage` instance is created based upon a
1267
:class:`MaildirMessage` instance, the following conversions take place:
1269
+-------------------+-------------------------------+
1270
| Resulting state | :class:`MaildirMessage` state |
1271
+===================+===============================+
1272
| "unseen" label | no S flag |
1273
+-------------------+-------------------------------+
1274
| "deleted" label | T flag |
1275
+-------------------+-------------------------------+
1276
| "answered" label | R flag |
1277
+-------------------+-------------------------------+
1278
| "forwarded" label | P flag |
1279
+-------------------+-------------------------------+
1281
When a :class:`BabylMessage` instance is created based upon an
1282
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1283
and :mailheader:`X-Status` headers are omitted and the following conversions
1286
+------------------+----------------------------------------------+
1287
| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1289
+==================+==============================================+
1290
| "unseen" label | no R flag |
1291
+------------------+----------------------------------------------+
1292
| "deleted" label | D flag |
1293
+------------------+----------------------------------------------+
1294
| "answered" label | A flag |
1295
+------------------+----------------------------------------------+
1297
When a :class:`BabylMessage` instance is created based upon an
1298
:class:`MHMessage` instance, the following conversions take place:
1300
+------------------+--------------------------+
1301
| Resulting state | :class:`MHMessage` state |
1302
+==================+==========================+
1303
| "unseen" label | "unseen" sequence |
1304
+------------------+--------------------------+
1305
| "answered" label | "replied" sequence |
1306
+------------------+--------------------------+
1309
.. _mailbox-mmdfmessage:
1311
:class:`MMDFMessage`
1312
^^^^^^^^^^^^^^^^^^^^
1315
.. class:: MMDFMessage([message])
1317
A message with MMDF-specific behaviors. Parameter *message* has the same meaning
1318
as with the :class:`Message` constructor.
1320
As with message in an mbox mailbox, MMDF messages are stored with the
1321
sender's address and the delivery date in an initial line beginning with
1322
"From ". Likewise, flags that indicate the state of the message are
1323
typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers.
1325
Conventional flags for MMDF messages are identical to those of mbox message
1328
+------+----------+--------------------------------+
1329
| Flag | Meaning | Explanation |
1330
+======+==========+================================+
1332
+------+----------+--------------------------------+
1333
| O | Old | Previously detected by MUA |
1334
+------+----------+--------------------------------+
1335
| D | Deleted | Marked for subsequent deletion |
1336
+------+----------+--------------------------------+
1337
| F | Flagged | Marked as important |
1338
+------+----------+--------------------------------+
1339
| A | Answered | Replied to |
1340
+------+----------+--------------------------------+
1342
The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
1343
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
1344
flags and headers typically appear in the order mentioned.
1346
:class:`MMDFMessage` instances offer the following methods, which are
1347
identical to those offered by :class:`mboxMessage`:
1350
.. method:: get_from()
1352
Return a string representing the "From " line that marks the start of the
1353
message in an mbox mailbox. The leading "From " and the trailing newline
1357
.. method:: set_from(from_[, time_=None])
1359
Set the "From " line to *from_*, which should be specified without a
1360
leading "From " or trailing newline. For convenience, *time_* may be
1361
specified and will be formatted appropriately and appended to *from_*. If
1362
*time_* is specified, it should be a :class:`struct_time` instance, a
1363
tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
1364
:meth:`time.gmtime`).
1367
.. method:: get_flags()
1369
Return a string specifying the flags that are currently set. If the
1370
message complies with the conventional format, the result is the
1371
concatenation in the following order of zero or one occurrence of each of
1372
``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1375
.. method:: set_flags(flags)
1377
Set the flags specified by *flags* and unset all others. Parameter *flags*
1378
should be the concatenation in any order of zero or more occurrences of
1379
each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1382
.. method:: add_flag(flag)
1384
Set the flag(s) specified by *flag* without changing other flags. To add
1385
more than one flag at a time, *flag* may be a string of more than one
1389
.. method:: remove_flag(flag)
1391
Unset the flag(s) specified by *flag* without changing other flags. To
1392
remove more than one flag at a time, *flag* maybe a string of more than
1395
When an :class:`MMDFMessage` instance is created based upon a
1396
:class:`MaildirMessage` instance, a "From " line is generated based upon the
1397
:class:`MaildirMessage` instance's delivery date, and the following conversions
1400
+-----------------+-------------------------------+
1401
| Resulting state | :class:`MaildirMessage` state |
1402
+=================+===============================+
1404
+-----------------+-------------------------------+
1405
| O flag | "cur" subdirectory |
1406
+-----------------+-------------------------------+
1408
+-----------------+-------------------------------+
1410
+-----------------+-------------------------------+
1412
+-----------------+-------------------------------+
1414
When an :class:`MMDFMessage` instance is created based upon an
1415
:class:`MHMessage` instance, the following conversions take place:
1417
+-------------------+--------------------------+
1418
| Resulting state | :class:`MHMessage` state |
1419
+===================+==========================+
1420
| R flag and O flag | no "unseen" sequence |
1421
+-------------------+--------------------------+
1422
| O flag | "unseen" sequence |
1423
+-------------------+--------------------------+
1424
| F flag | "flagged" sequence |
1425
+-------------------+--------------------------+
1426
| A flag | "replied" sequence |
1427
+-------------------+--------------------------+
1429
When an :class:`MMDFMessage` instance is created based upon a
1430
:class:`BabylMessage` instance, the following conversions take place:
1432
+-------------------+-----------------------------+
1433
| Resulting state | :class:`BabylMessage` state |
1434
+===================+=============================+
1435
| R flag and O flag | no "unseen" label |
1436
+-------------------+-----------------------------+
1437
| O flag | "unseen" label |
1438
+-------------------+-----------------------------+
1439
| D flag | "deleted" label |
1440
+-------------------+-----------------------------+
1441
| A flag | "answered" label |
1442
+-------------------+-----------------------------+
1444
When an :class:`MMDFMessage` instance is created based upon an
1445
:class:`mboxMessage` instance, the "From " line is copied and all flags directly
1448
+-----------------+----------------------------+
1449
| Resulting state | :class:`mboxMessage` state |
1450
+=================+============================+
1452
+-----------------+----------------------------+
1454
+-----------------+----------------------------+
1456
+-----------------+----------------------------+
1458
+-----------------+----------------------------+
1460
+-----------------+----------------------------+
1466
The following exception classes are defined in the :mod:`mailbox` module:
1469
.. exception:: Error()
1471
The based class for all other module-specific exceptions.
1474
.. exception:: NoSuchMailboxError()
1476
Raised when a mailbox is expected but is not found, such as when instantiating a
1477
:class:`Mailbox` subclass with a path that does not exist (and with the *create*
1478
parameter set to ``False``), or when opening a folder that does not exist.
1481
.. exception:: NotEmptyError()
1483
Raised when a mailbox is not empty but is expected to be, such as when deleting
1484
a folder that contains messages.
1487
.. exception:: ExternalClashError()
1489
Raised when some mailbox-related condition beyond the control of the program
1490
causes it to be unable to proceed, such as when failing to acquire a lock that
1491
another program already holds a lock, or when a uniquely-generated file name
1495
.. exception:: FormatError()
1497
Raised when the data in a file cannot be parsed, such as when an :class:`MH`
1498
instance attempts to read a corrupted :file:`.mh_sequences` file.
1501
.. _mailbox-examples:
1506
A simple example of printing the subjects of all messages in a mailbox that seem
1510
for message in mailbox.mbox('~/mbox'):
1511
subject = message['subject'] # Could possibly be None.
1512
if subject and 'python' in subject.lower():
1515
To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
1516
format-specific information that can be converted::
1519
destination = mailbox.MH('~/Mail')
1521
for message in mailbox.Babyl('~/RMAIL'):
1522
destination.add(mailbox.MHMessage(message))
1524
destination.unlock()
1526
This example sorts mail from several mailing lists into different mailboxes,
1527
being careful to avoid mail corruption due to concurrent modification by other
1528
programs, mail loss due to interruption of the program, or premature termination
1529
due to malformed messages in the mailbox::
1534
list_names = ('python-list', 'python-dev', 'python-bugs')
1536
boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names}
1537
inbox = mailbox.Maildir('~/Maildir', factory=None)
1539
for key in inbox.iterkeys():
1541
message = inbox[key]
1542
except email.Errors.MessageParseError:
1543
continue # The message is malformed. Just leave it.
1545
for name in list_names:
1546
list_id = message['list-id']
1547
if list_id and name in list_id:
1548
# Get mailbox to use
1551
# Write copy to disk before removing original.
1552
# If there's a crash, you might duplicate a message, but
1553
# that's better than losing a message completely.
1559
# Remove original message
1564
break # Found destination, so stop looking.
1566
for box in boxes.itervalues():