7.3.5 Examples

##
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')
    destination.lock()
    for message in mailbox.Babyl('~/RMAIL'):
        destination.add(MHMessage(message))
    destination.flush()
    destination.unlock()

This example sorts mail from several mailing lists into different mailboxes, 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', factory=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:
                # Get mailbox to use
                box = boxes[name]

                # Write copy to disk before removing original.
                # If there's a crash, you might duplicate a message, but
                # that's better than losing a message completely.
                box.lock()
                box.add(message)
                box.flush()
                box.unlock()

                # Remove original message
                inbox.lock()
                inbox.discard(key)
                inbox.flush()
                inbox.unlock()
                break               # Found destination, so stop looking.

    for box in boxes.itervalues():
        box.close()