7.3.5 Examples
A simple example of printing the subjects of all messages in a mailbox that seem interesting:
import mailbox for message in mailbox.mbox('~/mbox'): subject = message['subject'] # Could possibly be None. if subject and 'python' in subject.lower(): print subject
To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the format-specific information that can be converted:
import mailbox destination = mailbox.MH('~/Mail') for message in mailbox.Babyl('~/RMAIL'): destination.add(MHMessage(message))
An example of sorting mail from numerous mailing lists, being careful to avoid mail corruption due to concurrent modification by other programs, mail loss due to interruption of the program, or premature termination due to malformed messages in the mailbox:
import mailbox import email.Errors list_names = ('python-list', 'python-dev', 'python-bugs') boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names) inbox = mailbox.Maildir('~/Maildir', None) for key in inbox.iterkeys(): try: message = inbox[key] except email.Errors.MessageParseError: continue # The message is malformed. Just leave it. for name in list_names: list_id = message['list-id'] if list_id and name in list_id: box = boxes[name] box.lock() box.add(message) box.flush() # Write copy to disk before removing original. box.unlock() inbox.discard(key) break # Found destination, so stop looking. for box in boxes.itervalues(): box.close()