Debian Codegraph @

Doc/library/mailbox.rst

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