メールボックス中の面白そうなメッセージのサブジェクトを全て印字する簡単な例:
import mailbox
for message in mailbox.mbox('~/mbox'):
subject = message['subject'] # Could possibly be None.
if subject and 'python' in subject.lower():
print subject
Babyl メールボックスから MH メールボックスへ全てのメールをコピーし、 変換可能な全ての形式固有の情報を変換する:
import mailbox
destination = mailbox.MH('~/Mail')
for message in mailbox.Babyl('~/RMAIL'):
destination.add(MHMessage(message))
幾つかのメーリングリストのメールをソートする例。 他のプログラムと平行して変更を加えることでメールが破損したり、 プログラムを中断することでメールを失ったり、 はたまた半端なメッセージがメールボックス中にあることで途中で終了してしまう、 といったことを避けるように注意深く扱っている:
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()