email backup with Python

In my new project (involving spam) I’ve created a script for retrieving the messages locally, which you could also use for rapidly backing up your emails.

The script is aimed for retrieving the emails for multiple accounts using the POP3 protocol (via SSL).

#!/usr/bin/env python

import poplib, os

users = {
    "username1":"password1",
    "username2":"password2"
}

mail_server = 'mail.hosting.com'

for user in users:
    m = poplib.POP3_SSL(mail_server)
    m.user(user)
    m.pass_(users[user])
    num = len(m.list()[1])
    for i in range(1, num+1):
        uid  = m.retr(i)[2]
        mail = m.retr(i)[1]
        if not os.access(user, os.F_OK):
            os.mkdir(user, 0777)
        mfile  = user+'/'+str(uid)+'.txt'
        mstore = open(mfile, 'w')
        mstore.write("\n".join(mail))
        mstore.close()
    m.quit()

Of course you should replace poplib.POP3_SSL with poplib.POP3 if SSL is not supported by your mail server.

Hope you find it useful… going back to work.




2 Responses to “email backup with Python”


  1. nice work y0, thanx for the share

  2. David says:

    Quite simple but nice work.
    You should include some features like checking if incoming email is blacklisted or something…


Leave a Reply