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