Sunday, December 23, 2007

Converting Mac Address Book vCards Using Ruby

For sending out a large number of Christmas emails to family and friends, I wanted to try the commercial Campaign Monitor email service.

The email addresses were in Apple's Address book, in a group called "Christmas 2007" and were on OS 10.4 (Tiger).

Address Book exports vCards, and Campaign Monitor will let you upload a comma delimited file (cdf) like this:

Scott Schram,scott@some-example-domain.foo

First, I exported the Address Book group to a file vCards.vcf and wrote the Ruby program below to convert them to text format.

vCards can include more than one email, and even though there's a way to mark which email you prefer in the group in Address Book, that information is not reflected in the exported vCards.

So, the program extracts all emails, and for those few vCards that have more than one, I just manually edited the text file to remove the unwanted emails.

The vpim gem had errors with the format of the vCards from the 10.4.x Address Book, so I imported them into a 10.5 (Leopard) Address Book, exported them again, and then everything worked fine.

Campaign Monitor worked great, too!

#!/usr/bin/env ruby -v
#
# Requires gem vpim (0.360)
#
require 'vpim/vcard'

infile = File.open("vCards.vcf")
cards = Vpim::Vcard.decode(infile)

cards.sort_by{ |card| card['n'] }.each do |card|
  emails = card.emails.join(" ")
  puts "#{card['fn']},#{emails}"
end

0 comments: