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