blob: fc0ce8b4daf3e3bf9ddd8227e260414a21cc0a84 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`mailbox` --- Manipulate mailboxes in various formats
3==========================================================
4
5.. module:: mailbox
6 :synopsis: Manipulate mailboxes in various formats
7.. moduleauthor:: Gregory K. Johnson <gkj@gregorykjohnson.com>
8.. sectionauthor:: Gregory K. Johnson <gkj@gregorykjohnson.com>
9
10
11This module defines two classes, :class:`Mailbox` and :class:`Message`, for
12accessing 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`
15class with format-specific state and behavior. Supported mailbox formats are
16Maildir, mbox, MH, Babyl, and MMDF.
17
18
19.. seealso::
20
21 Module :mod:`email`
22 Represent and manipulate messages.
23
24
25.. _mailbox-objects:
26
27:class:`Mailbox` objects
28------------------------
29
30
31.. class:: Mailbox
32
33 A mailbox, which may be inspected and modified.
34
35The :class:`Mailbox` class defines an interface and is not intended to be
36instantiated. Instead, format-specific subclasses should inherit from
37:class:`Mailbox` and your code should instantiate a particular subclass.
38
39The :class:`Mailbox` interface is dictionary-like, with small keys corresponding
40to messages. Keys are issued by the :class:`Mailbox` instance with which they
41will be used and are only meaningful to that :class:`Mailbox` instance. A key
42continues to identify a message even if the corresponding message is modified,
43such as by replacing it with another message.
44
45Messages may be added to a :class:`Mailbox` instance using the set-like method
46:meth:`add` and removed using a ``del`` statement or the set-like methods
47:meth:`remove` and :meth:`discard`.
48
49:class:`Mailbox` interface semantics differ from dictionary semantics in some
50noteworthy ways. Each time a message is requested, a new representation
51(typically a :class:`Message` instance) is generated based upon the current
52state of the mailbox. Similarly, when a message is added to a :class:`Mailbox`
53instance, the provided message representation's contents are copied. In neither
54case is a reference to the message representation kept by the :class:`Mailbox`
55instance.
56
57The default :class:`Mailbox` iterator iterates over message representations, not
58keys as the default dictionary iterator does. Moreover, modification of a
59mailbox during iteration is safe and well-defined. Messages added to the mailbox
60after an iterator is created will not be seen by the iterator. Messages removed
61from the mailbox before the iterator yields them will be silently skipped,
62though using a key from an iterator may result in a :exc:`KeyError` exception if
63the corresponding message is subsequently removed.
64
65.. warning::
66
67 Be very cautious when modifying mailboxes that might be simultaneously changed
68 by some other process. The safest mailbox format to use for such tasks is
69 Maildir; try to avoid using single-file formats such as mbox for concurrent
70 writing. If you're modifying a mailbox, you *must* lock it by calling the
71 :meth:`lock` and :meth:`unlock` methods *before* reading any messages in the
72 file or making any changes by adding or deleting a message. Failing to lock the
73 mailbox runs the risk of losing messages or corrupting the entire mailbox.
74
75:class:`Mailbox` instances have the following methods:
76
77
78.. method:: Mailbox.add(message)
79
80 Add *message* to the mailbox and return the key that has been assigned to it.
81
82 Parameter *message* may be a :class:`Message` instance, an
83 :class:`email.Message.Message` instance, a string, or a file-like object (which
84 should be open in text mode). If *message* is an instance of the appropriate
85 format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage`
86 instance and this is an :class:`mbox` instance), its format-specific information
87 is used. Otherwise, reasonable defaults for format-specific information are
88 used.
89
90
91.. method:: Mailbox.remove(key)
92 Mailbox.__delitem__(key)
93 Mailbox.discard(key)
94
95 Delete the message corresponding to *key* from the mailbox.
96
97 If no such message exists, a :exc:`KeyError` exception is raised if the method
98 was called as :meth:`remove` or :meth:`__delitem__` but no exception is raised
99 if the method was called as :meth:`discard`. The behavior of :meth:`discard` may
100 be preferred if the underlying mailbox format supports concurrent modification
101 by other processes.
102
103
104.. method:: Mailbox.__setitem__(key, message)
105
106 Replace the message corresponding to *key* with *message*. Raise a
107 :exc:`KeyError` exception if no message already corresponds to *key*.
108
109 As with :meth:`add`, parameter *message* may be a :class:`Message` instance, an
110 :class:`email.Message.Message` instance, a string, or a file-like object (which
111 should be open in text mode). If *message* is an instance of the appropriate
112 format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage`
113 instance and this is an :class:`mbox` instance), its format-specific information
114 is used. Otherwise, the format-specific information of the message that
115 currently corresponds to *key* is left unchanged.
116
117
118.. method:: Mailbox.iterkeys()
119 Mailbox.keys()
120
121 Return an iterator over all keys if called as :meth:`iterkeys` or return a list
122 of keys if called as :meth:`keys`.
123
124
125.. method:: Mailbox.itervalues()
126 Mailbox.__iter__()
127 Mailbox.values()
128
129 Return an iterator over representations of all messages if called as
130 :meth:`itervalues` or :meth:`__iter__` or return a list of such representations
131 if called as :meth:`values`. The messages are represented as instances of the
132 appropriate format-specific :class:`Message` subclass unless a custom message
133 factory was specified when the :class:`Mailbox` instance was initialized.
134
135 .. note::
136
137 The behavior of :meth:`__iter__` is unlike that of dictionaries, which iterate
138 over keys.
139
140
141.. method:: Mailbox.iteritems()
142 Mailbox.items()
143
144 Return an iterator over (*key*, *message*) pairs, where *key* is a key and
145 *message* is a message representation, if called as :meth:`iteritems` or return
146 a list of such pairs if called as :meth:`items`. The messages are represented as
147 instances of the appropriate format-specific :class:`Message` subclass unless a
148 custom message factory was specified when the :class:`Mailbox` instance was
149 initialized.
150
151
152.. method:: Mailbox.get(key[, default=None])
153 Mailbox.__getitem__(key)
154
155 Return a representation of the message corresponding to *key*. If no such
156 message exists, *default* is returned if the method was called as :meth:`get`
157 and a :exc:`KeyError` exception is raised if the method was called as
158 :meth:`__getitem__`. The message is represented as an instance of the
159 appropriate format-specific :class:`Message` subclass unless a custom message
160 factory was specified when the :class:`Mailbox` instance was initialized.
161
162
163.. method:: Mailbox.get_message(key)
164
165 Return a representation of the message corresponding to *key* as an instance of
166 the appropriate format-specific :class:`Message` subclass, or raise a
167 :exc:`KeyError` exception if no such message exists.
168
169
170.. method:: Mailbox.get_string(key)
171
172 Return a string representation of the message corresponding to *key*, or raise a
173 :exc:`KeyError` exception if no such message exists.
174
175
176.. method:: Mailbox.get_file(key)
177
178 Return a file-like representation of the message corresponding to *key*, or
179 raise a :exc:`KeyError` exception if no such message exists. The file-like
180 object behaves as if open in binary mode. This file should be closed once it is
181 no longer needed.
182
183 .. note::
184
185 Unlike other representations of messages, file-like representations are not
186 necessarily independent of the :class:`Mailbox` instance that created them or of
187 the underlying mailbox. More specific documentation is provided by each
188 subclass.
189
190
Collin Winterc79461b2007-09-01 23:34:30 +0000191.. method:: Mailbox.__contains__(key)
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193 Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
194
195
196.. method:: Mailbox.__len__()
197
198 Return a count of messages in the mailbox.
199
200
201.. method:: Mailbox.clear()
202
203 Delete all messages from the mailbox.
204
205
206.. method:: Mailbox.pop(key[, default])
207
208 Return a representation of the message corresponding to *key* and delete the
209 message. If no such message exists, return *default* if it was supplied or else
210 raise a :exc:`KeyError` exception. The message is represented as an instance of
211 the appropriate format-specific :class:`Message` subclass unless a custom
212 message factory was specified when the :class:`Mailbox` instance was
213 initialized.
214
215
216.. method:: Mailbox.popitem()
217
218 Return an arbitrary (*key*, *message*) pair, where *key* is a key and *message*
219 is a message representation, and delete the corresponding message. If the
220 mailbox is empty, raise a :exc:`KeyError` exception. The message is represented
221 as an instance of the appropriate format-specific :class:`Message` subclass
222 unless a custom message factory was specified when the :class:`Mailbox` instance
223 was initialized.
224
225
226.. method:: Mailbox.update(arg)
227
228 Parameter *arg* should be a *key*-to-*message* mapping or an iterable of (*key*,
229 *message*) pairs. Updates the mailbox so that, for each given *key* and
230 *message*, the message corresponding to *key* is set to *message* as if by using
231 :meth:`__setitem__`. As with :meth:`__setitem__`, each *key* must already
232 correspond to a message in the mailbox or else a :exc:`KeyError` exception will
233 be raised, so in general it is incorrect for *arg* to be a :class:`Mailbox`
234 instance.
235
236 .. note::
237
238 Unlike with dictionaries, keyword arguments are not supported.
239
240
241.. method:: Mailbox.flush()
242
243 Write any pending changes to the filesystem. For some :class:`Mailbox`
244 subclasses, changes are always written immediately and :meth:`flush` does
245 nothing, but you should still make a habit of calling this method.
246
247
248.. method:: Mailbox.lock()
249
250 Acquire an exclusive advisory lock on the mailbox so that other processes know
251 not to modify it. An :exc:`ExternalClashError` is raised if the lock is not
252 available. The particular locking mechanisms used depend upon the mailbox
253 format. You should *always* lock the mailbox before making any modifications
254 to its contents.
255
256
257.. method:: Mailbox.unlock()
258
259 Release the lock on the mailbox, if any.
260
261
262.. method:: Mailbox.close()
263
264 Flush the mailbox, unlock it if necessary, and close any open files. For some
265 :class:`Mailbox` subclasses, this method does nothing.
266
267
268.. _mailbox-maildir:
269
270:class:`Maildir`
271^^^^^^^^^^^^^^^^
272
273
274.. class:: Maildir(dirname[, factory=rfc822.Message[, create=True]])
275
276 A subclass of :class:`Mailbox` for mailboxes in Maildir format. Parameter
277 *factory* is a callable object that accepts a file-like message representation
278 (which behaves as if opened in binary mode) and returns a custom representation.
279 If *factory* is ``None``, :class:`MaildirMessage` is used as the default message
280 representation. If *create* is ``True``, the mailbox is created if it does not
281 exist.
282
283 It is for historical reasons that *factory* defaults to :class:`rfc822.Message`
284 and that *dirname* is named as such rather than *path*. For a :class:`Maildir`
285 instance that behaves like instances of other :class:`Mailbox` subclasses, set
286 *factory* to ``None``.
287
288Maildir is a directory-based mailbox format invented for the qmail mail transfer
289agent and now widely supported by other programs. Messages in a Maildir mailbox
290are stored in separate files within a common directory structure. This design
291allows Maildir mailboxes to be accessed and modified by multiple unrelated
292programs without data corruption, so file locking is unnecessary.
293
294Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
295:file:`new`, and :file:`cur`. Messages are created momentarily in the
296:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to
297finalize delivery. A mail user agent may subsequently move the message to the
298:file:`cur` subdirectory and store information about the state of the message in
299a special "info" section appended to its file name.
300
301Folders of the style introduced by the Courier mail transfer agent are also
302supported. Any subdirectory of the main mailbox is considered a folder if
303``'.'`` is the first character in its name. Folder names are represented by
304:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
305mailbox but should not contain other folders. Instead, a logical nesting is
306indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
307
308.. note::
309
310 The Maildir specification requires the use of a colon (``':'``) in certain
311 message file names. However, some operating systems do not permit this character
312 in file names, If you wish to use a Maildir-like format on such an operating
313 system, you should specify another character to use instead. The exclamation
314 point (``'!'``) is a popular choice. For example::
315
316 import mailbox
317 mailbox.Maildir.colon = '!'
318
319 The :attr:`colon` attribute may also be set on a per-instance basis.
320
321:class:`Maildir` instances have all of the methods of :class:`Mailbox` in
322addition to the following:
323
324
325.. method:: Maildir.list_folders()
326
327 Return a list of the names of all folders.
328
329
330.. method:: Maildir.get_folder(folder)
331
332 Return a :class:`Maildir` instance representing the folder whose name is
333 *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder does not
334 exist.
335
336
337.. method:: Maildir.add_folder(folder)
338
339 Create a folder whose name is *folder* and return a :class:`Maildir` instance
340 representing it.
341
342
343.. method:: Maildir.remove_folder(folder)
344
345 Delete the folder whose name is *folder*. If the folder contains any messages, a
346 :exc:`NotEmptyError` exception will be raised and the folder will not be
347 deleted.
348
349
350.. method:: Maildir.clean()
351
352 Delete temporary files from the mailbox that have not been accessed in the last
353 36 hours. The Maildir specification says that mail-reading programs should do
354 this occasionally.
355
356Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
357remarks:
358
359
360.. method:: Maildir.add(message)
361 Maildir.__setitem__(key, message)
362 Maildir.update(arg)
363
364 .. warning::
365
366 These methods generate unique file names based upon the current process ID. When
367 using multiple threads, undetected name clashes may occur and cause corruption
368 of the mailbox unless threads are coordinated to avoid using these methods to
369 manipulate the same mailbox simultaneously.
370
371
372.. method:: Maildir.flush()
373
374 All changes to Maildir mailboxes are immediately applied, so this method does
375 nothing.
376
377
378.. method:: Maildir.lock()
379 Maildir.unlock()
380
381 Maildir mailboxes do not support (or require) locking, so these methods do
382 nothing.
383
384
385.. method:: Maildir.close()
386
387 :class:`Maildir` instances do not keep any open files and the underlying
388 mailboxes do not support locking, so this method does nothing.
389
390
391.. method:: Maildir.get_file(key)
392
393 Depending upon the host platform, it may not be possible to modify or remove the
394 underlying message while the returned file remains open.
395
396
397.. seealso::
398
399 `maildir man page from qmail <http://www.qmail.org/man/man5/maildir.html>`_
400 The original specification of the format.
401
402 `Using maildir format <http://cr.yp.to/proto/maildir.html>`_
403 Notes on Maildir by its inventor. Includes an updated name-creation scheme and
404 details on "info" semantics.
405
406 `maildir man page from Courier <http://www.courier-mta.org/?maildir.html>`_
407 Another specification of the format. Describes a common extension for supporting
408 folders.
409
410
411.. _mailbox-mbox:
412
413:class:`mbox`
414^^^^^^^^^^^^^
415
416
417.. class:: mbox(path[, factory=None[, create=True]])
418
419 A subclass of :class:`Mailbox` for mailboxes in mbox format. Parameter *factory*
420 is a callable object that accepts a file-like message representation (which
421 behaves as if opened in binary mode) and returns a custom representation. If
422 *factory* is ``None``, :class:`mboxMessage` is used as the default message
423 representation. If *create* is ``True``, the mailbox is created if it does not
424 exist.
425
426The mbox format is the classic format for storing mail on Unix systems. All
427messages in an mbox mailbox are stored in a single file with the beginning of
428each message indicated by a line whose first five characters are "From ".
429
430Several variations of the mbox format exist to address perceived shortcomings in
431the original. In the interest of compatibility, :class:`mbox` implements the
432original format, which is sometimes referred to as :dfn:`mboxo`. This means that
433the :mailheader:`Content-Length` header, if present, is ignored and that any
434occurrences of "From " at the beginning of a line in a message body are
435transformed to ">From " when storing the message, although occurences of ">From
436" are not transformed to "From " when reading the message.
437
438Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
439remarks:
440
441
442.. method:: mbox.get_file(key)
443
444 Using the file after calling :meth:`flush` or :meth:`close` on the :class:`mbox`
445 instance may yield unpredictable results or raise an exception.
446
447
448.. method:: mbox.lock()
449 mbox.unlock()
450
451 Three locking mechanisms are used---dot locking and, if available, the
452 :cfunc:`flock` and :cfunc:`lockf` system calls.
453
454
455.. seealso::
456
457 `mbox man page from qmail <http://www.qmail.org/man/man5/mbox.html>`_
458 A specification of the format and its variations.
459
460 `mbox man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mbox>`_
461 Another specification of the format, with details on locking.
462
463 `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html>`_
464 An argument for using the original mbox format rather than a variation.
465
466 `"mbox" is a family of several mutually incompatible mailbox formats <http://homepages.tesco.net./~J.deBoynePollard/FGA/mail-mbox-formats.html>`_
467 A history of mbox variations.
468
469
470.. _mailbox-mh:
471
472:class:`MH`
473^^^^^^^^^^^
474
475
476.. class:: MH(path[, factory=None[, create=True]])
477
478 A subclass of :class:`Mailbox` for mailboxes in MH format. Parameter *factory*
479 is a callable object that accepts a file-like message representation (which
480 behaves as if opened in binary mode) and returns a custom representation. If
481 *factory* is ``None``, :class:`MHMessage` is used as the default message
482 representation. If *create* is ``True``, the mailbox is created if it does not
483 exist.
484
485MH is a directory-based mailbox format invented for the MH Message Handling
486System, a mail user agent. Each message in an MH mailbox resides in its own
487file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in
488addition to messages. Folders may be nested indefinitely. MH mailboxes also
489support :dfn:`sequences`, which are named lists used to logically group messages
490without moving them to sub-folders. Sequences are defined in a file called
491:file:`.mh_sequences` in each folder.
492
493The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
494emulate all of :program:`mh`'s behaviors. In particular, it does not modify and
495is not affected by the :file:`context` or :file:`.mh_profile` files that are
496used by :program:`mh` to store its state and configuration.
497
498:class:`MH` instances have all of the methods of :class:`Mailbox` in addition to
499the following:
500
501
502.. method:: MH.list_folders()
503
504 Return a list of the names of all folders.
505
506
507.. method:: MH.get_folder(folder)
508
509 Return an :class:`MH` instance representing the folder whose name is *folder*. A
510 :exc:`NoSuchMailboxError` exception is raised if the folder does not exist.
511
512
513.. method:: MH.add_folder(folder)
514
515 Create a folder whose name is *folder* and return an :class:`MH` instance
516 representing it.
517
518
519.. method:: MH.remove_folder(folder)
520
521 Delete the folder whose name is *folder*. If the folder contains any messages, a
522 :exc:`NotEmptyError` exception will be raised and the folder will not be
523 deleted.
524
525
526.. method:: MH.get_sequences()
527
528 Return a dictionary of sequence names mapped to key lists. If there are no
529 sequences, the empty dictionary is returned.
530
531
532.. method:: MH.set_sequences(sequences)
533
534 Re-define the sequences that exist in the mailbox based upon *sequences*, a
535 dictionary of names mapped to key lists, like returned by :meth:`get_sequences`.
536
537
538.. method:: MH.pack()
539
540 Rename messages in the mailbox as necessary to eliminate gaps in numbering.
541 Entries in the sequences list are updated correspondingly.
542
543 .. note::
544
545 Already-issued keys are invalidated by this operation and should not be
546 subsequently used.
547
548Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
549remarks:
550
551
552.. method:: MH.remove(key)
553 MH.__delitem__(key)
554 MH.discard(key)
555
556 These methods immediately delete the message. The MH convention of marking a
557 message for deletion by prepending a comma to its name is not used.
558
559
560.. method:: MH.lock()
561 MH.unlock()
562
563 Three locking mechanisms are used---dot locking and, if available, the
564 :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking the
565 mailbox means locking the :file:`.mh_sequences` file and, only for the duration
566 of any operations that affect them, locking individual message files.
567
568
569.. method:: MH.get_file(key)
570
571 Depending upon the host platform, it may not be possible to remove the
572 underlying message while the returned file remains open.
573
574
575.. method:: MH.flush()
576
577 All changes to MH mailboxes are immediately applied, so this method does
578 nothing.
579
580
581.. method:: MH.close()
582
583 :class:`MH` instances do not keep any open files, so this method is equivelant
584 to :meth:`unlock`.
585
586
587.. seealso::
588
589 `nmh - Message Handling System <http://www.nongnu.org/nmh/>`_
590 Home page of :program:`nmh`, an updated version of the original :program:`mh`.
591
592 `MH & nmh: Email for Users & Programmers <http://www.ics.uci.edu/~mh/book/>`_
593 A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information
594 on the mailbox format.
595
596
597.. _mailbox-babyl:
598
599:class:`Babyl`
600^^^^^^^^^^^^^^
601
602
603.. class:: Babyl(path[, factory=None[, create=True]])
604
605 A subclass of :class:`Mailbox` for mailboxes in Babyl format. Parameter
606 *factory* is a callable object that accepts a file-like message representation
607 (which behaves as if opened in binary mode) and returns a custom representation.
608 If *factory* is ``None``, :class:`BabylMessage` is used as the default message
609 representation. If *create* is ``True``, the mailbox is created if it does not
610 exist.
611
612Babyl is a single-file mailbox format used by the Rmail mail user agent included
613with Emacs. The beginning of a message is indicated by a line containing the two
614characters Control-Underscore (``'\037'``) and Control-L (``'\014'``). The end
615of a message is indicated by the start of the next message or, in the case of
616the last message, a line containing a Control-Underscore (``'\037'``)
617character.
618
619Messages in a Babyl mailbox have two sets of headers, original headers and
620so-called visible headers. Visible headers are typically a subset of the
621original headers that have been reformatted or abridged to be more
622attractive. Each message in a Babyl mailbox also has an accompanying list of
623:dfn:`labels`, or short strings that record extra information about the message,
624and a list of all user-defined labels found in the mailbox is kept in the Babyl
625options section.
626
627:class:`Babyl` instances have all of the methods of :class:`Mailbox` in addition
628to the following:
629
630
631.. method:: Babyl.get_labels()
632
633 Return a list of the names of all user-defined labels used in the mailbox.
634
635 .. note::
636
637 The actual messages are inspected to determine which labels exist in the mailbox
638 rather than consulting the list of labels in the Babyl options section, but the
639 Babyl section is updated whenever the mailbox is modified.
640
641Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
642remarks:
643
644
645.. method:: Babyl.get_file(key)
646
647 In Babyl mailboxes, the headers of a message are not stored contiguously with
648 the body of the message. To generate a file-like representation, the headers and
649 body are copied together into a :class:`StringIO` instance (from the
650 :mod:`StringIO` module), which has an API identical to that of a file. As a
651 result, the file-like object is truly independent of the underlying mailbox but
652 does not save memory compared to a string representation.
653
654
655.. method:: Babyl.lock()
656 Babyl.unlock()
657
658 Three locking mechanisms are used---dot locking and, if available, the
659 :cfunc:`flock` and :cfunc:`lockf` system calls.
660
661
662.. seealso::
663
664 `Format of Version 5 Babyl Files <http://quimby.gnus.org/notes/BABYL>`_
665 A specification of the Babyl format.
666
667 `Reading Mail with Rmail <http://www.gnu.org/software/emacs/manual/html_node/Rmail.html>`_
668 The Rmail manual, with some information on Babyl semantics.
669
670
671.. _mailbox-mmdf:
672
673:class:`MMDF`
674^^^^^^^^^^^^^
675
676
677.. class:: MMDF(path[, factory=None[, create=True]])
678
679 A subclass of :class:`Mailbox` for mailboxes in MMDF format. Parameter *factory*
680 is a callable object that accepts a file-like message representation (which
681 behaves as if opened in binary mode) and returns a custom representation. If
682 *factory* is ``None``, :class:`MMDFMessage` is used as the default message
683 representation. If *create* is ``True``, the mailbox is created if it does not
684 exist.
685
686MMDF is a single-file mailbox format invented for the Multichannel Memorandum
687Distribution Facility, a mail transfer agent. Each message is in the same form
688as an mbox message but is bracketed before and after by lines containing four
689Control-A (``'\001'``) characters. As with the mbox format, the beginning of
690each message is indicated by a line whose first five characters are "From ", but
691additional occurrences of "From " are not transformed to ">From " when storing
692messages because the extra message separator lines prevent mistaking such
693occurrences for the starts of subsequent messages.
694
695Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
696remarks:
697
698
699.. method:: MMDF.get_file(key)
700
701 Using the file after calling :meth:`flush` or :meth:`close` on the :class:`MMDF`
702 instance may yield unpredictable results or raise an exception.
703
704
705.. method:: MMDF.lock()
706 MMDF.unlock()
707
708 Three locking mechanisms are used---dot locking and, if available, the
709 :cfunc:`flock` and :cfunc:`lockf` system calls.
710
711
712.. seealso::
713
714 `mmdf man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mmdf>`_
715 A specification of MMDF format from the documentation of tin, a newsreader.
716
717 `MMDF <http://en.wikipedia.org/wiki/MMDF>`_
718 A Wikipedia article describing the Multichannel Memorandum Distribution
719 Facility.
720
721
722.. _mailbox-message-objects:
723
724:class:`Message` objects
725------------------------
726
727
728.. class:: Message([message])
729
730 A subclass of the :mod:`email.Message` module's :class:`Message`. Subclasses of
731 :class:`mailbox.Message` add mailbox-format-specific state and behavior.
732
733 If *message* is omitted, the new instance is created in a default, empty state.
734 If *message* is an :class:`email.Message.Message` instance, its contents are
735 copied; furthermore, any format-specific information is converted insofar as
736 possible if *message* is a :class:`Message` instance. If *message* is a string
737 or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
738 and parsed.
739
740The format-specific state and behaviors offered by subclasses vary, but in
741general it is only the properties that are not specific to a particular mailbox
742that are supported (although presumably the properties are specific to a
743particular mailbox format). For example, file offsets for single-file mailbox
744formats and file names for directory-based mailbox formats are not retained,
745because they are only applicable to the original mailbox. But state such as
746whether a message has been read by the user or marked as important is retained,
747because it applies to the message itself.
748
749There is no requirement that :class:`Message` instances be used to represent
750messages retrieved using :class:`Mailbox` instances. In some situations, the
751time and memory required to generate :class:`Message` representations might not
752not acceptable. For such situations, :class:`Mailbox` instances also offer
753string and file-like representations, and a custom message factory may be
754specified when a :class:`Mailbox` instance is initialized.
755
756
757.. _mailbox-maildirmessage:
758
759:class:`MaildirMessage`
760^^^^^^^^^^^^^^^^^^^^^^^
761
762
763.. class:: MaildirMessage([message])
764
765 A message with Maildir-specific behaviors. Parameter *message* has the same
766 meaning as with the :class:`Message` constructor.
767
768Typically, a mail user agent application moves all of the messages in the
769:file:`new` subdirectory to the :file:`cur` subdirectory after the first time
770the user opens and closes the mailbox, recording that the messages are old
771whether or not they've actually been read. Each message in :file:`cur` has an
772"info" section added to its file name to store information about its state.
773(Some mail readers may also add an "info" section to messages in :file:`new`.)
774The "info" section may take one of two forms: it may contain "2," followed by a
775list of standardized flags (e.g., "2,FR") or it may contain "1," followed by
776so-called experimental information. Standard flags for Maildir messages are as
777follows:
778
779+------+---------+--------------------------------+
780| Flag | Meaning | Explanation |
781+======+=========+================================+
782| D | Draft | Under composition |
783+------+---------+--------------------------------+
784| F | Flagged | Marked as important |
785+------+---------+--------------------------------+
786| P | Passed | Forwarded, resent, or bounced |
787+------+---------+--------------------------------+
788| R | Replied | Replied to |
789+------+---------+--------------------------------+
790| S | Seen | Read |
791+------+---------+--------------------------------+
792| T | Trashed | Marked for subsequent deletion |
793+------+---------+--------------------------------+
794
795:class:`MaildirMessage` instances offer the following methods:
796
797
798.. method:: MaildirMessage.get_subdir()
799
800 Return either "new" (if the message should be stored in the :file:`new`
801 subdirectory) or "cur" (if the message should be stored in the :file:`cur`
802 subdirectory).
803
804 .. note::
805
806 A message is typically moved from :file:`new` to :file:`cur` after its mailbox
807 has been accessed, whether or not the message is has been read. A message
808 ``msg`` has been read if ``"S" not in msg.get_flags()`` is ``True``.
809
810
811.. method:: MaildirMessage.set_subdir(subdir)
812
813 Set the subdirectory the message should be stored in. Parameter *subdir* must be
814 either "new" or "cur".
815
816
817.. method:: MaildirMessage.get_flags()
818
819 Return a string specifying the flags that are currently set. If the message
820 complies with the standard Maildir format, the result is the concatenation in
821 alphabetical order of zero or one occurrence of each of ``'D'``, ``'F'``,
822 ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string is returned if no flags
823 are set or if "info" contains experimental semantics.
824
825
826.. method:: MaildirMessage.set_flags(flags)
827
828 Set the flags specified by *flags* and unset all others.
829
830
831.. method:: MaildirMessage.add_flag(flag)
832
833 Set the flag(s) specified by *flag* without changing other flags. To add more
834 than one flag at a time, *flag* may be a string of more than one character. The
835 current "info" is overwritten whether or not it contains experimental
836 information rather than flags.
837
838
839.. method:: MaildirMessage.remove_flag(flag)
840
841 Unset the flag(s) specified by *flag* without changing other flags. To remove
842 more than one flag at a time, *flag* maybe a string of more than one character.
843 If "info" contains experimental information rather than flags, the current
844 "info" is not modified.
845
846
847.. method:: MaildirMessage.get_date()
848
849 Return the delivery date of the message as a floating-point number representing
850 seconds since the epoch.
851
852
853.. method:: MaildirMessage.set_date(date)
854
855 Set the delivery date of the message to *date*, a floating-point number
856 representing seconds since the epoch.
857
858
859.. method:: MaildirMessage.get_info()
860
861 Return a string containing the "info" for a message. This is useful for
862 accessing and modifying "info" that is experimental (i.e., not a list of flags).
863
864
865.. method:: MaildirMessage.set_info(info)
866
867 Set "info" to *info*, which should be a string.
868
869When a :class:`MaildirMessage` instance is created based upon an
870:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
871and :mailheader:`X-Status` headers are omitted and the following conversions
872take place:
873
874+--------------------+----------------------------------------------+
875| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
876| | state |
877+====================+==============================================+
878| "cur" subdirectory | O flag |
879+--------------------+----------------------------------------------+
880| F flag | F flag |
881+--------------------+----------------------------------------------+
882| R flag | A flag |
883+--------------------+----------------------------------------------+
884| S flag | R flag |
885+--------------------+----------------------------------------------+
886| T flag | D flag |
887+--------------------+----------------------------------------------+
888
889When a :class:`MaildirMessage` instance is created based upon an
890:class:`MHMessage` instance, the following conversions take place:
891
892+-------------------------------+--------------------------+
893| Resulting state | :class:`MHMessage` state |
894+===============================+==========================+
895| "cur" subdirectory | "unseen" sequence |
896+-------------------------------+--------------------------+
897| "cur" subdirectory and S flag | no "unseen" sequence |
898+-------------------------------+--------------------------+
899| F flag | "flagged" sequence |
900+-------------------------------+--------------------------+
901| R flag | "replied" sequence |
902+-------------------------------+--------------------------+
903
904When a :class:`MaildirMessage` instance is created based upon a
905:class:`BabylMessage` instance, the following conversions take place:
906
907+-------------------------------+-------------------------------+
908| Resulting state | :class:`BabylMessage` state |
909+===============================+===============================+
910| "cur" subdirectory | "unseen" label |
911+-------------------------------+-------------------------------+
912| "cur" subdirectory and S flag | no "unseen" label |
913+-------------------------------+-------------------------------+
914| P flag | "forwarded" or "resent" label |
915+-------------------------------+-------------------------------+
916| R flag | "answered" label |
917+-------------------------------+-------------------------------+
918| T flag | "deleted" label |
919+-------------------------------+-------------------------------+
920
921
922.. _mailbox-mboxmessage:
923
924:class:`mboxMessage`
925^^^^^^^^^^^^^^^^^^^^
926
927
928.. class:: mboxMessage([message])
929
930 A message with mbox-specific behaviors. Parameter *message* has the same meaning
931 as with the :class:`Message` constructor.
932
933Messages in an mbox mailbox are stored together in a single file. The sender's
934envelope address and the time of delivery are typically stored in a line
935beginning with "From " that is used to indicate the start of a message, though
936there is considerable variation in the exact format of this data among mbox
937implementations. Flags that indicate the state of the message, such as whether
938it has been read or marked as important, are typically stored in
939:mailheader:`Status` and :mailheader:`X-Status` headers.
940
941Conventional flags for mbox messages are as follows:
942
943+------+----------+--------------------------------+
944| Flag | Meaning | Explanation |
945+======+==========+================================+
946| R | Read | Read |
947+------+----------+--------------------------------+
948| O | Old | Previously detected by MUA |
949+------+----------+--------------------------------+
950| D | Deleted | Marked for subsequent deletion |
951+------+----------+--------------------------------+
952| F | Flagged | Marked as important |
953+------+----------+--------------------------------+
954| A | Answered | Replied to |
955+------+----------+--------------------------------+
956
957The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
958"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
959flags and headers typically appear in the order mentioned.
960
961:class:`mboxMessage` instances offer the following methods:
962
963
964.. method:: mboxMessage.get_from()
965
966 Return a string representing the "From " line that marks the start of the
967 message in an mbox mailbox. The leading "From " and the trailing newline are
968 excluded.
969
970
971.. method:: mboxMessage.set_from(from_[, time_=None])
972
973 Set the "From " line to *from_*, which should be specified without a leading
974 "From " or trailing newline. For convenience, *time_* may be specified and will
975 be formatted appropriately and appended to *from_*. If *time_* is specified, it
976 should be a :class:`struct_time` instance, a tuple suitable for passing to
977 :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`).
978
979
980.. method:: mboxMessage.get_flags()
981
982 Return a string specifying the flags that are currently set. If the message
983 complies with the conventional format, the result is the concatenation in the
984 following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``,
985 ``'F'``, and ``'A'``.
986
987
988.. method:: mboxMessage.set_flags(flags)
989
990 Set the flags specified by *flags* and unset all others. Parameter *flags*
991 should be the concatenation in any order of zero or more occurrences of each of
992 ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
993
994
995.. method:: mboxMessage.add_flag(flag)
996
997 Set the flag(s) specified by *flag* without changing other flags. To add more
998 than one flag at a time, *flag* may be a string of more than one character.
999
1000
1001.. method:: mboxMessage.remove_flag(flag)
1002
1003 Unset the flag(s) specified by *flag* without changing other flags. To remove
1004 more than one flag at a time, *flag* maybe a string of more than one character.
1005
1006When an :class:`mboxMessage` instance is created based upon a
1007:class:`MaildirMessage` instance, a "From " line is generated based upon the
1008:class:`MaildirMessage` instance's delivery date, and the following conversions
1009take place:
1010
1011+-----------------+-------------------------------+
1012| Resulting state | :class:`MaildirMessage` state |
1013+=================+===============================+
1014| R flag | S flag |
1015+-----------------+-------------------------------+
1016| O flag | "cur" subdirectory |
1017+-----------------+-------------------------------+
1018| D flag | T flag |
1019+-----------------+-------------------------------+
1020| F flag | F flag |
1021+-----------------+-------------------------------+
1022| A flag | R flag |
1023+-----------------+-------------------------------+
1024
1025When an :class:`mboxMessage` instance is created based upon an
1026:class:`MHMessage` instance, the following conversions take place:
1027
1028+-------------------+--------------------------+
1029| Resulting state | :class:`MHMessage` state |
1030+===================+==========================+
1031| R flag and O flag | no "unseen" sequence |
1032+-------------------+--------------------------+
1033| O flag | "unseen" sequence |
1034+-------------------+--------------------------+
1035| F flag | "flagged" sequence |
1036+-------------------+--------------------------+
1037| A flag | "replied" sequence |
1038+-------------------+--------------------------+
1039
1040When an :class:`mboxMessage` instance is created based upon a
1041:class:`BabylMessage` instance, the following conversions take place:
1042
1043+-------------------+-----------------------------+
1044| Resulting state | :class:`BabylMessage` state |
1045+===================+=============================+
1046| R flag and O flag | no "unseen" label |
1047+-------------------+-----------------------------+
1048| O flag | "unseen" label |
1049+-------------------+-----------------------------+
1050| D flag | "deleted" label |
1051+-------------------+-----------------------------+
1052| A flag | "answered" label |
1053+-------------------+-----------------------------+
1054
1055When a :class:`Message` instance is created based upon an :class:`MMDFMessage`
1056instance, the "From " line is copied and all flags directly correspond:
1057
1058+-----------------+----------------------------+
1059| Resulting state | :class:`MMDFMessage` state |
1060+=================+============================+
1061| R flag | R flag |
1062+-----------------+----------------------------+
1063| O flag | O flag |
1064+-----------------+----------------------------+
1065| D flag | D flag |
1066+-----------------+----------------------------+
1067| F flag | F flag |
1068+-----------------+----------------------------+
1069| A flag | A flag |
1070+-----------------+----------------------------+
1071
1072
1073.. _mailbox-mhmessage:
1074
1075:class:`MHMessage`
1076^^^^^^^^^^^^^^^^^^
1077
1078
1079.. class:: MHMessage([message])
1080
1081 A message with MH-specific behaviors. Parameter *message* has the same meaning
1082 as with the :class:`Message` constructor.
1083
1084MH messages do not support marks or flags in the traditional sense, but they do
1085support sequences, which are logical groupings of arbitrary messages. Some mail
1086reading programs (although not the standard :program:`mh` and :program:`nmh`)
1087use sequences in much the same way flags are used with other formats, as
1088follows:
1089
1090+----------+------------------------------------------+
1091| Sequence | Explanation |
1092+==========+==========================================+
1093| unseen | Not read, but previously detected by MUA |
1094+----------+------------------------------------------+
1095| replied | Replied to |
1096+----------+------------------------------------------+
1097| flagged | Marked as important |
1098+----------+------------------------------------------+
1099
1100:class:`MHMessage` instances offer the following methods:
1101
1102
1103.. method:: MHMessage.get_sequences()
1104
1105 Return a list of the names of sequences that include this message.
1106
1107
1108.. method:: MHMessage.set_sequences(sequences)
1109
1110 Set the list of sequences that include this message.
1111
1112
1113.. method:: MHMessage.add_sequence(sequence)
1114
1115 Add *sequence* to the list of sequences that include this message.
1116
1117
1118.. method:: MHMessage.remove_sequence(sequence)
1119
1120 Remove *sequence* from the list of sequences that include this message.
1121
1122When an :class:`MHMessage` instance is created based upon a
1123:class:`MaildirMessage` instance, the following conversions take place:
1124
1125+--------------------+-------------------------------+
1126| Resulting state | :class:`MaildirMessage` state |
1127+====================+===============================+
1128| "unseen" sequence | no S flag |
1129+--------------------+-------------------------------+
1130| "replied" sequence | R flag |
1131+--------------------+-------------------------------+
1132| "flagged" sequence | F flag |
1133+--------------------+-------------------------------+
1134
1135When an :class:`MHMessage` instance is created based upon an
1136:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1137and :mailheader:`X-Status` headers are omitted and the following conversions
1138take place:
1139
1140+--------------------+----------------------------------------------+
1141| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1142| | state |
1143+====================+==============================================+
1144| "unseen" sequence | no R flag |
1145+--------------------+----------------------------------------------+
1146| "replied" sequence | A flag |
1147+--------------------+----------------------------------------------+
1148| "flagged" sequence | F flag |
1149+--------------------+----------------------------------------------+
1150
1151When an :class:`MHMessage` instance is created based upon a
1152:class:`BabylMessage` instance, the following conversions take place:
1153
1154+--------------------+-----------------------------+
1155| Resulting state | :class:`BabylMessage` state |
1156+====================+=============================+
1157| "unseen" sequence | "unseen" label |
1158+--------------------+-----------------------------+
1159| "replied" sequence | "answered" label |
1160+--------------------+-----------------------------+
1161
1162
1163.. _mailbox-babylmessage:
1164
1165:class:`BabylMessage`
1166^^^^^^^^^^^^^^^^^^^^^
1167
1168
1169.. class:: BabylMessage([message])
1170
1171 A message with Babyl-specific behaviors. Parameter *message* has the same
1172 meaning as with the :class:`Message` constructor.
1173
1174Certain message labels, called :dfn:`attributes`, are defined by convention to
1175have special meanings. The attributes are as follows:
1176
1177+-----------+------------------------------------------+
1178| Label | Explanation |
1179+===========+==========================================+
1180| unseen | Not read, but previously detected by MUA |
1181+-----------+------------------------------------------+
1182| deleted | Marked for subsequent deletion |
1183+-----------+------------------------------------------+
1184| filed | Copied to another file or mailbox |
1185+-----------+------------------------------------------+
1186| answered | Replied to |
1187+-----------+------------------------------------------+
1188| forwarded | Forwarded |
1189+-----------+------------------------------------------+
1190| edited | Modified by the user |
1191+-----------+------------------------------------------+
1192| resent | Resent |
1193+-----------+------------------------------------------+
1194
1195By default, Rmail displays only visible headers. The :class:`BabylMessage`
1196class, though, uses the original headers because they are more complete. Visible
1197headers may be accessed explicitly if desired.
1198
1199:class:`BabylMessage` instances offer the following methods:
1200
1201
1202.. method:: BabylMessage.get_labels()
1203
1204 Return a list of labels on the message.
1205
1206
1207.. method:: BabylMessage.set_labels(labels)
1208
1209 Set the list of labels on the message to *labels*.
1210
1211
1212.. method:: BabylMessage.add_label(label)
1213
1214 Add *label* to the list of labels on the message.
1215
1216
1217.. method:: BabylMessage.remove_label(label)
1218
1219 Remove *label* from the list of labels on the message.
1220
1221
1222.. method:: BabylMessage.get_visible()
1223
1224 Return an :class:`Message` instance whose headers are the message's visible
1225 headers and whose body is empty.
1226
1227
1228.. method:: BabylMessage.set_visible(visible)
1229
1230 Set the message's visible headers to be the same as the headers in *message*.
1231 Parameter *visible* should be a :class:`Message` instance, an
1232 :class:`email.Message.Message` instance, a string, or a file-like object (which
1233 should be open in text mode).
1234
1235
1236.. method:: BabylMessage.update_visible()
1237
1238 When a :class:`BabylMessage` instance's original headers are modified, the
1239 visible headers are not automatically modified to correspond. This method
1240 updates the visible headers as follows: each visible header with a corresponding
1241 original header is set to the value of the original header, each visible header
1242 without a corresponding original header is removed, and any of
1243 :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`,
1244 :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are present
1245 in the original headers but not the visible headers are added to the visible
1246 headers.
1247
1248When a :class:`BabylMessage` instance is created based upon a
1249:class:`MaildirMessage` instance, the following conversions take place:
1250
1251+-------------------+-------------------------------+
1252| Resulting state | :class:`MaildirMessage` state |
1253+===================+===============================+
1254| "unseen" label | no S flag |
1255+-------------------+-------------------------------+
1256| "deleted" label | T flag |
1257+-------------------+-------------------------------+
1258| "answered" label | R flag |
1259+-------------------+-------------------------------+
1260| "forwarded" label | P flag |
1261+-------------------+-------------------------------+
1262
1263When a :class:`BabylMessage` instance is created based upon an
1264:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
1265and :mailheader:`X-Status` headers are omitted and the following conversions
1266take place:
1267
1268+------------------+----------------------------------------------+
1269| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` |
1270| | state |
1271+==================+==============================================+
1272| "unseen" label | no R flag |
1273+------------------+----------------------------------------------+
1274| "deleted" label | D flag |
1275+------------------+----------------------------------------------+
1276| "answered" label | A flag |
1277+------------------+----------------------------------------------+
1278
1279When a :class:`BabylMessage` instance is created based upon an
1280:class:`MHMessage` instance, the following conversions take place:
1281
1282+------------------+--------------------------+
1283| Resulting state | :class:`MHMessage` state |
1284+==================+==========================+
1285| "unseen" label | "unseen" sequence |
1286+------------------+--------------------------+
1287| "answered" label | "replied" sequence |
1288+------------------+--------------------------+
1289
1290
1291.. _mailbox-mmdfmessage:
1292
1293:class:`MMDFMessage`
1294^^^^^^^^^^^^^^^^^^^^
1295
1296
1297.. class:: MMDFMessage([message])
1298
1299 A message with MMDF-specific behaviors. Parameter *message* has the same meaning
1300 as with the :class:`Message` constructor.
1301
1302As with message in an mbox mailbox, MMDF messages are stored with the sender's
1303address and the delivery date in an initial line beginning with "From ".
1304Likewise, flags that indicate the state of the message are typically stored in
1305:mailheader:`Status` and :mailheader:`X-Status` headers.
1306
1307Conventional flags for MMDF messages are identical to those of mbox message and
1308are as follows:
1309
1310+------+----------+--------------------------------+
1311| Flag | Meaning | Explanation |
1312+======+==========+================================+
1313| R | Read | Read |
1314+------+----------+--------------------------------+
1315| O | Old | Previously detected by MUA |
1316+------+----------+--------------------------------+
1317| D | Deleted | Marked for subsequent deletion |
1318+------+----------+--------------------------------+
1319| F | Flagged | Marked as important |
1320+------+----------+--------------------------------+
1321| A | Answered | Replied to |
1322+------+----------+--------------------------------+
1323
1324The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
1325"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
1326flags and headers typically appear in the order mentioned.
1327
1328:class:`MMDFMessage` instances offer the following methods, which are identical
1329to those offered by :class:`mboxMessage`:
1330
1331
1332.. method:: MMDFMessage.get_from()
1333
1334 Return a string representing the "From " line that marks the start of the
1335 message in an mbox mailbox. The leading "From " and the trailing newline are
1336 excluded.
1337
1338
1339.. method:: MMDFMessage.set_from(from_[, time_=None])
1340
1341 Set the "From " line to *from_*, which should be specified without a leading
1342 "From " or trailing newline. For convenience, *time_* may be specified and will
1343 be formatted appropriately and appended to *from_*. If *time_* is specified, it
1344 should be a :class:`struct_time` instance, a tuple suitable for passing to
1345 :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`).
1346
1347
1348.. method:: MMDFMessage.get_flags()
1349
1350 Return a string specifying the flags that are currently set. If the message
1351 complies with the conventional format, the result is the concatenation in the
1352 following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``,
1353 ``'F'``, and ``'A'``.
1354
1355
1356.. method:: MMDFMessage.set_flags(flags)
1357
1358 Set the flags specified by *flags* and unset all others. Parameter *flags*
1359 should be the concatenation in any order of zero or more occurrences of each of
1360 ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
1361
1362
1363.. method:: MMDFMessage.add_flag(flag)
1364
1365 Set the flag(s) specified by *flag* without changing other flags. To add more
1366 than one flag at a time, *flag* may be a string of more than one character.
1367
1368
1369.. method:: MMDFMessage.remove_flag(flag)
1370
1371 Unset the flag(s) specified by *flag* without changing other flags. To remove
1372 more than one flag at a time, *flag* maybe a string of more than one character.
1373
1374When an :class:`MMDFMessage` instance is created based upon a
1375:class:`MaildirMessage` instance, a "From " line is generated based upon the
1376:class:`MaildirMessage` instance's delivery date, and the following conversions
1377take place:
1378
1379+-----------------+-------------------------------+
1380| Resulting state | :class:`MaildirMessage` state |
1381+=================+===============================+
1382| R flag | S flag |
1383+-----------------+-------------------------------+
1384| O flag | "cur" subdirectory |
1385+-----------------+-------------------------------+
1386| D flag | T flag |
1387+-----------------+-------------------------------+
1388| F flag | F flag |
1389+-----------------+-------------------------------+
1390| A flag | R flag |
1391+-----------------+-------------------------------+
1392
1393When an :class:`MMDFMessage` instance is created based upon an
1394:class:`MHMessage` instance, the following conversions take place:
1395
1396+-------------------+--------------------------+
1397| Resulting state | :class:`MHMessage` state |
1398+===================+==========================+
1399| R flag and O flag | no "unseen" sequence |
1400+-------------------+--------------------------+
1401| O flag | "unseen" sequence |
1402+-------------------+--------------------------+
1403| F flag | "flagged" sequence |
1404+-------------------+--------------------------+
1405| A flag | "replied" sequence |
1406+-------------------+--------------------------+
1407
1408When an :class:`MMDFMessage` instance is created based upon a
1409:class:`BabylMessage` instance, the following conversions take place:
1410
1411+-------------------+-----------------------------+
1412| Resulting state | :class:`BabylMessage` state |
1413+===================+=============================+
1414| R flag and O flag | no "unseen" label |
1415+-------------------+-----------------------------+
1416| O flag | "unseen" label |
1417+-------------------+-----------------------------+
1418| D flag | "deleted" label |
1419+-------------------+-----------------------------+
1420| A flag | "answered" label |
1421+-------------------+-----------------------------+
1422
1423When an :class:`MMDFMessage` instance is created based upon an
1424:class:`mboxMessage` instance, the "From " line is copied and all flags directly
1425correspond:
1426
1427+-----------------+----------------------------+
1428| Resulting state | :class:`mboxMessage` state |
1429+=================+============================+
1430| R flag | R flag |
1431+-----------------+----------------------------+
1432| O flag | O flag |
1433+-----------------+----------------------------+
1434| D flag | D flag |
1435+-----------------+----------------------------+
1436| F flag | F flag |
1437+-----------------+----------------------------+
1438| A flag | A flag |
1439+-----------------+----------------------------+
1440
1441
1442Exceptions
1443----------
1444
1445The following exception classes are defined in the :mod:`mailbox` module:
1446
1447
1448.. class:: Error()
1449
1450 The based class for all other module-specific exceptions.
1451
1452
1453.. class:: NoSuchMailboxError()
1454
1455 Raised when a mailbox is expected but is not found, such as when instantiating a
1456 :class:`Mailbox` subclass with a path that does not exist (and with the *create*
1457 parameter set to ``False``), or when opening a folder that does not exist.
1458
1459
1460.. class:: NotEmptyErrorError()
1461
1462 Raised when a mailbox is not empty but is expected to be, such as when deleting
1463 a folder that contains messages.
1464
1465
1466.. class:: ExternalClashError()
1467
1468 Raised when some mailbox-related condition beyond the control of the program
1469 causes it to be unable to proceed, such as when failing to acquire a lock that
1470 another program already holds a lock, or when a uniquely-generated file name
1471 already exists.
1472
1473
1474.. class:: FormatError()
1475
1476 Raised when the data in a file cannot be parsed, such as when an :class:`MH`
1477 instance attempts to read a corrupted :file:`.mh_sequences` file.
1478
1479
1480.. _mailbox-deprecated:
1481
1482Deprecated classes and methods
1483------------------------------
1484
1485Older versions of the :mod:`mailbox` module do not support modification of
1486mailboxes, such as adding or removing message, and do not provide classes to
1487represent format-specific message properties. For backward compatibility, the
1488older mailbox classes are still available, but the newer classes should be used
1489in preference to them.
1490
1491Older mailbox objects support only iteration and provide a single public method:
1492
1493
1494.. method:: oldmailbox.next()
1495
1496 Return the next message in the mailbox, created with the optional *factory*
1497 argument passed into the mailbox object's constructor. By default this is an
1498 :class:`rfc822.Message` object (see the :mod:`rfc822` module). Depending on the
1499 mailbox implementation the *fp* attribute of this object may be a true file
1500 object or a class instance simulating a file object, taking care of things like
1501 message boundaries if multiple mail messages are contained in a single file,
1502 etc. If no more messages are available, this method returns ``None``.
1503
1504Most of the older mailbox classes have names that differ from the current
1505mailbox class names, except for :class:`Maildir`. For this reason, the new
1506:class:`Maildir` class defines a :meth:`next` method and its constructor differs
1507slightly from those of the other new mailbox classes.
1508
1509The older mailbox classes whose names are not the same as their newer
1510counterparts are as follows:
1511
1512
1513.. class:: UnixMailbox(fp[, factory])
1514
1515 Access to a classic Unix-style mailbox, where all messages are contained in a
1516 single file and separated by ``From`` (a.k.a. ``From_``) lines. The file object
1517 *fp* points to the mailbox file. The optional *factory* parameter is a callable
1518 that should create new message objects. *factory* is called with one argument,
1519 *fp* by the :meth:`next` method of the mailbox object. The default is the
1520 :class:`rfc822.Message` class (see the :mod:`rfc822` module -- and the note
1521 below).
1522
1523 .. note::
1524
1525 For reasons of this module's internal implementation, you will probably want to
1526 open the *fp* object in binary mode. This is especially important on Windows.
1527
1528 For maximum portability, messages in a Unix-style mailbox are separated by any
1529 line that begins exactly with the string ``'From '`` (note the trailing space)
1530 if preceded by exactly two newlines. Because of the wide-range of variations in
1531 practice, nothing else on the ``From_`` line should be considered. However, the
1532 current implementation doesn't check for the leading two newlines. This is
1533 usually fine for most applications.
1534
1535 The :class:`UnixMailbox` class implements a more strict version of ``From_``
1536 line checking, using a regular expression that usually correctly matched
1537 ``From_`` delimiters. It considers delimiter line to be separated by ``From
1538 name time`` lines. For maximum portability, use the
1539 :class:`PortableUnixMailbox` class instead. This class is identical to
1540 :class:`UnixMailbox` except that individual messages are separated by only
1541 ``From`` lines.
1542
1543 For more information, see `Configuring Netscape Mail on Unix: Why the
1544 Content-Length Format is Bad
1545 <http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html>`_.
1546
1547
1548.. class:: PortableUnixMailbox(fp[, factory])
1549
1550 A less-strict version of :class:`UnixMailbox`, which considers only the ``From``
1551 at the beginning of the line separating messages. The "*name* *time*" portion
1552 of the From line is ignored, to protect against some variations that are
1553 observed in practice. This works since lines in the message which begin with
1554 ``'From '`` are quoted by mail handling software at delivery-time.
1555
1556
1557.. class:: MmdfMailbox(fp[, factory])
1558
1559 Access an MMDF-style mailbox, where all messages are contained in a single file
1560 and separated by lines consisting of 4 control-A characters. The file object
1561 *fp* points to the mailbox file. Optional *factory* is as with the
1562 :class:`UnixMailbox` class.
1563
1564
1565.. class:: MHMailbox(dirname[, factory])
1566
1567 Access an MH mailbox, a directory with each message in a separate file with a
1568 numeric name. The name of the mailbox directory is passed in *dirname*.
1569 *factory* is as with the :class:`UnixMailbox` class.
1570
1571
1572.. class:: BabylMailbox(fp[, factory])
1573
1574 Access a Babyl mailbox, which is similar to an MMDF mailbox. In Babyl format,
1575 each message has two sets of headers, the *original* headers and the *visible*
1576 headers. The original headers appear before a line containing only ``'*** EOOH
1577 ***'`` (End-Of-Original-Headers) and the visible headers appear after the
1578 ``EOOH`` line. Babyl-compliant mail readers will show you only the visible
1579 headers, and :class:`BabylMailbox` objects will return messages containing only
1580 the visible headers. You'll have to do your own parsing of the mailbox file to
1581 get at the original headers. Mail messages start with the EOOH line and end
1582 with a line containing only ``'\037\014'``. *factory* is as with the
1583 :class:`UnixMailbox` class.
1584
1585If you wish to use the older mailbox classes with the :mod:`email` module rather
1586than the deprecated :mod:`rfc822` module, you can do so as follows::
1587
1588 import email
1589 import email.Errors
1590 import mailbox
1591
1592 def msgfactory(fp):
1593 try:
1594 return email.message_from_file(fp)
1595 except email.Errors.MessageParseError:
1596 # Don't return None since that will
1597 # stop the mailbox iterator
1598 return ''
1599
1600 mbox = mailbox.UnixMailbox(fp, msgfactory)
1601
1602Alternatively, if you know your mailbox contains only well-formed MIME messages,
1603you can simplify this to::
1604
1605 import email
1606 import mailbox
1607
1608 mbox = mailbox.UnixMailbox(fp, email.message_from_file)
1609
1610
1611.. _mailbox-examples:
1612
1613Examples
1614--------
1615
1616A simple example of printing the subjects of all messages in a mailbox that seem
1617interesting::
1618
1619 import mailbox
1620 for message in mailbox.mbox('~/mbox'):
1621 subject = message['subject'] # Could possibly be None.
1622 if subject and 'python' in subject.lower():
Georg Brandl6911e3c2007-09-04 07:15:32 +00001623 print(subject)
Georg Brandl116aa622007-08-15 14:28:22 +00001624
1625To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
1626format-specific information that can be converted::
1627
1628 import mailbox
1629 destination = mailbox.MH('~/Mail')
1630 destination.lock()
1631 for message in mailbox.Babyl('~/RMAIL'):
1632 destination.add(MHMessage(message))
1633 destination.flush()
1634 destination.unlock()
1635
1636This example sorts mail from several mailing lists into different mailboxes,
1637being careful to avoid mail corruption due to concurrent modification by other
1638programs, mail loss due to interruption of the program, or premature termination
1639due to malformed messages in the mailbox::
1640
1641 import mailbox
1642 import email.Errors
1643
1644 list_names = ('python-list', 'python-dev', 'python-bugs')
1645
1646 boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names)
1647 inbox = mailbox.Maildir('~/Maildir', factory=None)
1648
1649 for key in inbox.iterkeys():
1650 try:
1651 message = inbox[key]
1652 except email.Errors.MessageParseError:
1653 continue # The message is malformed. Just leave it.
1654
1655 for name in list_names:
1656 list_id = message['list-id']
1657 if list_id and name in list_id:
1658 # Get mailbox to use
1659 box = boxes[name]
1660
1661 # Write copy to disk before removing original.
1662 # If there's a crash, you might duplicate a message, but
1663 # that's better than losing a message completely.
1664 box.lock()
1665 box.add(message)
1666 box.flush()
1667 box.unlock()
1668
1669 # Remove original message
1670 inbox.lock()
1671 inbox.discard(key)
1672 inbox.flush()
1673 inbox.unlock()
1674 break # Found destination, so stop looking.
1675
1676 for box in boxes.itervalues():
1677 box.close()
1678