Pages

Monday, September 7, 2009

Programmatic Gmail authentication with urllib2

   The python urllib2 library can be used to automate login to sites requiring authentication. Below I used it to authenticate to Gmail, get the atom mails feed, and parse the feed with feedparser library from M. Pilgrim.  References contain lot of examples and documentation. 
import urllib2
import logging
import feedparser

def auth(user, passwd):
 auth_handler = urllib2.HTTPBasicAuthHandler()
 auth_handler.add_password(
  realm='New mail feed',
  uri='https://mail.google.com',
  user='%s@gmail.com' % user,
  passwd=passwd
 )
 opener = urllib2.build_opener(auth_handler)
 urllib2.install_opener(opener)  
 
    try:
  feed = urllib2.urlopen('https://mail.google.com/mail/feed/atom')
 except urllib2.HTTPError, e:
  logging.error('The server couldn\'t fulfill the request.')
  logging.error('Error code: %s ', e.code)
  exit(1)
 except urllib2.URLError, e:
  logging.error('We failed to reach a server.')
  logging.error('Reason: %s .', e.reason)
  exit(2)
 except DownloadError, e:
  logging.error('Download error: %s.', e)
  exit(3)
 except Exception, e:
  logging.error('Other exception in urlopen: %s', e)
  exit(4)
  
 logging.info('Feed opened')
 return feed.read()

 def read_mail(feed):
  # Parse the Atom feed
  atom = feedparser.parse(feed)
  
  num_email = len(atom.entries)

  for i in range(num_email):
   mail = atom.entries[i]
            . . . . . .


References:

No comments:

Post a Comment