#!/usr/bin/env python # This is largely based on archive.py which came with libgmail and # was under the GPL 2.0, so this is also released under the GPL 2.0 # see file gpl.txt for more info. # At the moment, this is fairly dumb and just gets everything. # It has no concept of previously downloaded mail yet. # On the plus side, it gets labels as folders and even gets your spam # folder. # 5/12/2007 # v0.5 # John C. Vernaleo # john@netpurgatory.com import getpass import datetime import time import re import sys #This is the only non-standard library. import libgmail # This is the time to wait in between folders in seconds. # Set it to whatever you want. I choose 10 seconds in the hopes # that this would not make the gmail servers angry. wait=10 def get_from(message,lname): finddate=re.compile('^Date:') datepart=[] eachline=message.split("\n") for line in(eachline): if finddate.search(line): datepart=finddate.split(line) if datepart: datepart[1]=datepart[1].replace(",","").strip() dtemp=datepart[1].split(" ") #This order seems to be the only way pine and mutt are okay with. date=dtemp[0]+" "+dtemp[2]+" "+dtemp[1]+" "+dtemp[4]+" "+dtemp[5]+" "+dtemp[3] else: #In case we can't find the time, use the current time (and the hell #with timezones). date=datetime.datetime.now().strftime("%a May %d %I:%M:%S %Y") newf="From "+lname+"@gmail.com "+date+"\n" return(newf) def write_folder(ga,name,lname): stamp=str(datetime.date.today()) if name in libgmail.STANDARD_FOLDERS: result = ga.getMessagesByFolder(name, True) else: result = ga.getMessagesByLabel(name, True) mbox = [] if len(result): for thread in result: #print thread.id, len(thread), thread.subject for msg in thread: #print " ", msg.id, msg.number, msg.subject source = msg.source.replace("\r","").lstrip() newfrom=get_from(source,lname) mbox.append(newfrom) mbox.append(source) mbox.append("\n\n") open("%s-%s-%s.mbox" % (lname, name, stamp), "w").writelines(mbox) else: print "No threads found in `%s`." % name if __name__ == "__main__": lname = raw_input("Gmail account name: ") pw=getpass.getpass("Password: ") ga=libgmail.GmailAccount(lname,pw) print "\nPlease wait, logging in..." try: ga.login() except libgmail.GmailLoginFailure: print "\nLogin failed. (Wrong username/password?)" else: print "Log in successful.\n" searches = libgmail.STANDARD_FOLDERS + ga.getLabelNames() for folder in(searches): print folder write_folder(ga,folder,lname) time.sleep(wait) print "\nAll done."