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, https://mail.google.com/mail/feed/atom. 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('https://mail.google.com/mail/feed/atom')
try:
    h = urllib2.urlopen(req)
except IOError, e:
    pass
e.headers['www-authenticate']

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', 'https://mail.google.com', \
    'user@gmail.com', 'password')
op = urllib2.build_opener(ah)
urllib2.install_opener(op)
res = urllib2.urlopen('https://mail.google.com/mail/feed/atom')

lines = ''.join(res.readlines())
e = fromstring(lines)
fc = e.find('{http://purl.org/atom/ns#}fullcount')
print 'You have %i unread mail(s) in your GMail account' % int(fc.text)
Share

2 Comments

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>