Fun with Python and Gmail API

Yesterday I decided to play with Gmail's API in order to grab my contacts. To my surprise, it was a snap. Google has instructions for python Here, I wrote my example using Python 2.5 on OS X. Once I had unzipped the GData contents, I just changed to the GData directory and ran "sudo python setup.py install" and I was ready to go.

#################################

# javazquez.com

# Google GMAIL API example

##################################

import gdata.contacts.service

user = '[email protected]'

pwd = 'password'

client2 = gdata.contacts.service.ContactsService()

# Authenticate using your Google Docs email address

# and password.

client2.ClientLogin(user, pwd)

contacts_feed = client2.GetContactsFeed()


################################################

# NOTE: The GetContactsFeed does not give back

#		all contacts.

#              This 'problem' can be solved by looping

#		until the contacts_feed.GetNextLink

#             returns  None.

################################################

l=[]

while(contacts_feed) :

	for x in contacts_feed.entry:

		l.append([x.title.text, x.email[0].address])

	ret = contacts_feed.GetNextLink()

 	contacts_feed = client2.GetContactsFeed(ret.href)  if(ret) else ret


print "here are your %d contacts" % len(l)

for contact in l:

	print "%s -> %s" % (contact[0],contact[1])

Output

here are your xxxx contacts
ANDREW  -> [email protected]
...