0

I'm using imaplib to fetch emails for several accounts (Gmail, Yahoo..). What is the best way to store emails locally (including attachments).

Is there any way to pickle and store emails as file? Is it possible to store emails as bytes and retrieve them later as mail object?

I'll try to save mail in separate folder with each field in JSON file and attachment as separate files, but I was wondering if there is a native way of doing it.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
sstevan
  • 477
  • 2
  • 9
  • 25

1 Answers1

0

There are already several established ways to store mailboxes (i.e. a list of emails). Popular examples are Maildir and mbox.

Python includes the mailbox module which can handle them:

Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.

You can of course roll your own solution, pickle them or dump them as JSON to a file, but if you use one of the common formats, you gain compatibility with other programs (importing them into Thunderbird, for example).

Carsten
  • 17,991
  • 4
  • 48
  • 53
  • Thanks. I'll try to combine `mailbox` and `imaplib`. – sstevan Aug 07 '16 at 16:54
  • Good luck. This should help you: http://stackoverflow.com/questions/29432981/saving-imap-messages-with-python-mailbox-module – Carsten Aug 07 '16 at 16:57
  • I'm solving the same problem. One obstacle is that imaplib returns a "message_set" and I can't find any documentation on what, exactly, that is, or how to convert it to a python email.Message that I can then hand to the mailbox Maildir. – Steven J Owens Apr 21 '22 at 19:37