archiving labels or folders from gmail

I was recently asked by someone who uses google mail for their domain if it was somehow possible to download all the emails from a just certain label or folder. Of course the web interface doesnt offer any help with this, and I dont know if any of the common free IMAP clients support archiving only a part of a mailbox in an open format.

They add labels to all mail that matches a project, and when the project is closed, they burn all the related files to DVD for archiving, they just got stuck on fetching the emails. This is a bit specific, but just in case anyone else finds themselves in a similar situation, heres a useful little python script to download gmail to .eml files, which can be opened with just about any email client, and even a text editor if needed, they can also be injected into another mail system if needed.

It asks for an IMAP email address and password (I think IMAP is enabled by default, but might be an idea to double check if you get errors) and then saves all mail for the chosen label to a subdirectory named after the label. It has very little error checking, and may well cause irreversable damage to the liver and kidneys, but it worked for me. On windows, install activepython first :)

#!/usr/bin/env python                     
#getmailbylabel.py                        
#author captainmish@gmail.com             

import imaplib
import getpass
import string
import os     


def getlogin(username, password, server="imap.gmail.com", serverport=993):
    M = imaplib.IMAP4_SSL(server, serverport)                             
    M.login(gusername, gpassword)                                         
    return M                                                              
                                                                          
def selectfolder(M):                                                      
    folderlist = M.list()[1]                                              
    folderdict = {}                                                       
    for line in range(len(folderlist)):                                   
        folderdict[line+1] = folderlist[line].partition('"/"')[2].strip()
        print line+1, folderlist[line].partition('"/"')[2].strip()        

    folderchoice = raw_input('Please enter a label number to download: ')
    selectedfolder = folderdict[int(folderchoice)]                       
    return selectedfolder                                                

def writemails(M, selectedfolder):
    print 'Getting all mail with %s label' % selectedfolder
    M.select(selectedfolder)                               
    validchars = '-_.() %s%s' % (string.ascii_letters, string.digits)
    createdirectory = ''.join(c for c in selectedfolder.strip() if c in validchars)
    print 'Creating %s directory' % createdirectory,
    if os.access('.', 6):
        try:
            os.mkdir(createdirectory)
            print '\t... done'
        except:
            print '\t... error'
            print 'Please make sure you can write to the current directory and try again'

    typ, data = M.search(None, 'ALL')
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
        subject = (M.fetch(num, '(BODY[HEADER.FIELDS (SUBJECT)])'))[1]
        filename = ''.join(c for c in subject[0][1].strip() if c in validchars)[8:]
        gfile = open(createdirectory + '/' + num + '-' + filename + '.eml', 'w')
        gfile.write(data[0][1].replace('\r\n','\n'))
        print 'Writing file "%s"' % filename,
        gfile.close()
        print '\t... done'

if __name__ == '__main__':
    gusername = raw_input('Google username: ')
    gpassword = getpass.getpass('Password for ' + gusername + ': ')
    M = getlogin(gusername, gpassword)
    selectedfolder = selectfolder(M)
    writemails(M, selectedfolder)