Need to import your emails into a local email client? Getting fired from your job and need your old emails for legal proceedings? Just want a backup of all your emails? Whatever the reason, it's not difficult to do in Python with the excellent exchangelib library doing most of the heavy lifting. The solution below downloads and saves all of your emails/attachments into a standard mbox file, which can be read by a number of command-line and GUI mail clients and tools.

In the maildump365.py script, set the USERNAME, PASSWORD, and SERVER variables as appropriate. For Office 365, the server is outlook.office365.com.

The maildump365.py script automatically saves the IDs of the messages it downloads and processes successfully. Thus, it can be run multiple times without issue, only downloading new emails it has not previously encountered.

The maildump365.py script takes two required arguments: the first is the name of one of the well-known top-level folders supported by exchangelib (e.g. inbox, sent, trash, etc.), and the second is the name of the output mbox file.

Occasionally exchangelib will fail to parse a message due to API errors, parsing errors, etc. In this case you can simply run exchangelib again and it will attempt to refetch the remaining messages, which will be appended to the end of the mbox file. If this happens, the sort_mbox.py script (which takes the path to the mbox file as its only argument) can be used to sort the messages in chronological order.