Playing with Python and GMail

For a project that I’m considering I’ve spent a few hours looking into using Python to access GMail. There’s a nice Python library called libgmail, but it’s a bit overkill since all I want is to see how many unread emails I have. After a bit of searching I found ot that there’s an atom feed that can be used to do exactly that, It uses basic authentication, your GMail username and password. So, I started looking at Python and HTTP.

urllib2 seemed to fit the bill. It has a class called HTTPBasicAuthHandler to do the authentication and everything. I used the following code (entered in ipython of course):

import urllib2
req = urllib2.Request('')
    h = urllib2.urlopen(req)
except IOError, e:

It should produce something like 'BASIC realm="New mail feed"'. Now we can do the proper connection, pull down the atom entry. I opted to use elementtree since it’s so easy to use. Here’s the full code I put together for this little experiment:

import urllib2
from elementtree.ElementTree import fromstring

ah = urllib2.HTTPBasicAuthHandler()
ah.add_password('New mail feed', '', \
    '', 'password')
op = urllib2.build_opener(ah)
res = urllib2.urlopen('')

lines = ''.join(res.readlines())
e = fromstring(lines)
fc = e.find('{}fullcount')
print 'You have %i unread mail(s) in your GMail account' % int(fc.text)


Thanks a ton, this is exactly what I was looking for, trying to do the same thing. :)

Leave a comment