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)
![[Digg]](http://therning.org/magnus/wp-content/plugins/bookmarkify/digg.png)
![[Reddit]](http://therning.org/magnus/wp-content/plugins/bookmarkify/reddit.png)
claudiney:
href=”https://mail.google.com/”>https://mail.google.com
14 August 2005, 8:34 pmLJ:
Thanks a ton, this is exactly what I was looking for, trying to do the same thing.
1 July 2006, 7:27 pm