Creating a local backup for your Emails

Do you want to download your Emails to your local system? Does your email provider not allow you to download specific emails? Do you have a some knowledge of Python Scripting?  If your answers to your above questions were “yes”, then you’ve come to the right place.If you want to get all your Emails data at one go, you can follow this video(for Gmail).

For the purposes of this tutorial we will be using the imap protocol to access and download the mail content.

TL;DR – Here’s the code gist

1. Logging to the Email service

Protip: You might want to use app passwords instead of your original password.

2. Selecting a mailbox

A mailbox is a folder that you can use to sort your emails. Some common mailboxes are – “[Gmail]/Starred”,”[Gmail]/Spam”,”INBOX”.
Display a list of all available mailboxes with the following code:.

and then select a mailbox using

conn.select(mailbox)

3. Getting the Email content

You might want to refer to IMAP search manual before you start using this parameter. The default parameter is ALL.

Putting it all together

3 comments On Creating a local backup for your Emails

  • Getting an error –
    Couldnt Parse message: b’4′ ‘charmap’ codec can’t encode character ‘\u25b8’ in position 31206: character maps to

  • Dear Ashish, first of all, thank you for sharing your knowledge.

    I would like to use your python script to backup my yahoo mail account(s) to my local HDD (automate the process). I use Linux (hope you too!). Also would like to backup gmail, but gmail has new credential restrictions, as you must already know (oauth2 authentication). Suggestions 1) your script should download and save a eml format file for each message from yahoo/gmail (including in the body the attachments ) . 2) each mailbox folder should be a sub-directory in the main backup/ folder. 2.1) folder name for each email account should be sub-directory in backup/ example: /backup/yourmail.yahoo/inbox/ 3) additional code is needed (a extra) to verbose downloaded messages, and be able to extract attachments. Can you help and update ? That would be a great “hit” in opensource community!

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar

About Me

About Me

Hey, I am Thomas Ashish Cherian. What I cannot create, I do not understand.

Social Profiles