LibGmaili不错,还可以将Gmail里邮件列表存档


               
               
               
                #!/usr/bin/env python
import os, sys
from time import gmtime, strftime
from ConfigParser import ConfigParser
from optparse import OptionParser
import base64
import libgmail
from packages import utils
def getGmailAccount():
    conf = ConfigParser()
    conf.read(os.path.join(os.getenv('HOME'), '.GmailAccount.txt'))
    user = conf.get('gmail', 'user')
    pw = conf.get('gmail', 'passwd')
    ga = libgmail.GmailAccount(user, base64.decodestring(utils.decrypt(pw)))
    print "\nPlease wait, logging in..."
    try:
        ga.login()
    except libgmail.GmailLoginFailure:
        print "\nLogin failed. (Wrong username/password?)"
    else:
        print "Log in successful.\n"
    return ga
def archive(ga):
    searches = libgmail.STANDARD_FOLDERS + ga.getLabelNames()
    while 1:
        try:
            print "Select folder or label to archive: (Ctrl-C to exit)"
            print "Note: *All* pages of results will be archived."
            for optionId, optionName in enumerate(searches):
                print "  %d. %s" % (optionId, optionName)
            name = searches[int(raw_input("Choice: "))]
            if name in libgmail.STANDARD_FOLDERS:
                result = ga.getMessagesByFolder(name, True)
            else:
                result = ga.getMessagesByLabel(name, True)
            if len(result):
                import time
                message_id = []
                fp = open(os.path.join(os.getenv('HOME'), 'Mail', name), 'a+')
                lines = fp.readlines()
                for line in lines:
                    if line.find('Message-ID') != -1:
                        #print 'line:', line[13:-2]
                        message_id.append(line[13:-2])   
                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()
                        flag = False
                        for line in source.splitlines():
                            if line.find('Message-ID') != -1:
                                #print 'source:', line[13:-1]
                                if line[13:-1] in message_id:
                                    flag = True
                                    break
                        if flag: break
                        fp.write('From - ' + \
                                  strftime("%a %b %d %H:%M:%S %Y",
                                  gmtime()) + '\n')
                        fp.write(source)
                        fp.write('\n\n')
            else:
                print "No threads found in `%s`." % name
        except KeyboardInterrupt:
            break
if __name__ == '__main__':
    parser = OptionParser(usage='%prog [-e] addr [-d] [-a] args...',
                          version='%prog 1.0')
    parser.add_option('-e', '--email',
                      dest='addr',
                      default='No.0023@gmail.com',
                      help='to email address')
    parser.add_option('-d',
                      dest='atta',
                      action='store_true',
                      default=False,
                      help='attach flag')
    parser.add_option('-a', '--archive',
                      dest='archive',
                      action='store_true',
                      default=False,
                      help='archive lable flag')
    (options, args) = parser.parse_args()
    if not options.archive and not args:
        print "No files to send!"
        sys.exit(1)
    
    ga = getGmailAccount()
    if options.archive:
        archive(ga)
        sys.exit(0)
    sign = '''
--
Best Regards,
    No.23
----
No.0023@gmail.com
'''
    print 'Send to ...', options.addr
    for arg in args:
        if options.atta is False:
            data = open(arg).read()
            data += sign
            msg = libgmail.GmailComposedMessage(
                  options.addr,
                  arg,
                  data)
        else:
            data = sign
            atta = arg
            msg = libgmail.GmailComposedMessage(
                  options.addr,
                  arg,
                  data,
                  filenames = [atta])
        if ga.sendMessage(msg):
            print 'Message sent %s successfully.' % arg
        else:
            print 'Could not send message.'
    print 'Done.'