1. Why Backup Google Mail?
With the amount of storage space that Google gives for its mail service, you might wonder why you would want to backup your account. There are several reasons why this is not as strange an idea as it may seem.
First, it is bad IT practice to store too much information in any one place without sufficient backup. Accidents happen.
Second, if you find yourself unable to connect for any reason, a local copy can be quite helpful. Accidents happen.
Third, while the possibility may seem remote, Google reserves the right at any time to suspend your account without warning (see Section 4.3 of the TOS). "That won't happen to me - I haven't done anything wrong!" you say. Well, eh-hem, accidents happen.
Fourth, you may ultimately decide to move your mail to another provider and want to move all of your old messages as well. This tip will help you create your own Google Mail archive.
In order to download all of your mail from Google, you must first have POP access enabled. See Heinz Tschabitscher's guide on accessing your Google account via POP3 to affect this.
2. The Template
Next, we will simply adopt the information in the guide "Retrieving POP3 Email with poplib" to fit Google's servers. At the end of that guide, we had the following code:
import getpass, poplib
user = raw_input('Username:')
server = raw_input('Server Address:')
type = raw_input('Encrypted with SSL (Y/N):')
port = raw_input('Port:')
if type=="Y":
Mailbox = poplib.POP3_SSL(server, port)
else:
Mailbox = poplib.POP3(server, port)
Mailbox.user(user)
Mailbox.pass_(getpass.getpass())
messageCount = len(Mailbox.list()[1])
for i in range(messageCount):
for j in Mailbox.retr(i+1)[1]:
print j
3. The Code
To access Google's servers, we can assume POP3 over SSL and can hardwire the server and port number. After that, it is a small matter of asking for the login details and looping through the message count. The final program looks like this:
#!/usr/bin/env python
import getpass, poplib
user = raw_input('Username:')
Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995')
Mailbox.user(user)
Mailbox.pass_(getpass.getpass())
messageCount = len(Mailbox.list()[1])
for i in range(messageCount):
for j in Mailbox.retr(i+1)[1]:
print j
If you are on Windows, you may need to adapt the
bang line.
Then, when run, the script prints your mailbox to the screen. With a bit of extra coding, you can then write it to a file for backup.
