PageRenderTime 38ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/library/mailbox.rst

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