~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Doc/library/mailbox.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

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