Friday, September 25, 2009

Importing your Thunderbird contacts to GMail.

I found myself needing to import my Thunderbird contacts to GMail. After asking the internets Thunderbird provides an option to export contacts as a CSV file and GMail provides an option to import contacts from a CSV file. Cool I thought and proceeded to something that should take me a couple of minutes to complete.
Of course surprise, surprise the CSV format outputted from Thunderbird does not produce the expected results when imported to GMail. So I quickly hacked up the following Python script to generate a GMail friendly csv file from a csv file exported from Thunderbird. Note that in order to use it you must have Python installed in your PC.
import sys
import csv

def transform(filename_in, filename_out):
  output_list = []
  try:
      file_input = open(filename_in)

      csv_input = csv.reader(file_input)
    
      for row in csv_input:
          entry_list = []
          entry_list.append(row[0])
          entry_list.append(row[1])
          if(output_list):
              entry_list.append(row[4])
          else:
              entry_list.append('Email Address')
            
          output_list.append(entry_list)

      file_input.close()
        
  except IOError:
      print 'Could not open file %s. '\
            'Make sure that the file exists.' % filename_in
      sys.exit(1)
        
  try:  
      file_output  = open(filename_out, "wb")
      csv_output = csv.writer(file_output)

      for row in output_list:
          csv_output.writerow(row)
        
      file_output.close()

  except IOError:
      print 'Could not open file %s. '\
            'Make sure that the file can be written.' % filename_out  
      sys.exit(1)
        

if __name__ == '__main__':
  if len(sys.argv) != 3:
      print "Usage: %s [input csv file] [output csv file]" % sys.argv[0]
      sys.exit(1)

  transform(sys.argv[1],sys.argv[2])
So to actually import your contacts from your Thunderbird email client to GMail:
  • In Thunderbird select Address Book -> Tools -> Export
  • In the export dialog select "Comma separated values" as the output type and save it somewhere (i.e. /home/foo/export.csv)
  • Grab the script above and save it somewhere with a name of your choice (i.e. converter.py)
  • Run the script with arguments the name of the file exported from Thunderbird and the name of the output file (i.e. python converter.py /home/foo/export.csv /home/foo/gmail_import.csv)
  • Open up GMail contacts and select "Import"
  • Choose the file outputted by the script (i.e. /home/foo/gmail_import.csv) and proceed to importing.
  • Enjoy

No comments:

Post a Comment