Home > python > Check Gmail for new messages

Check Gmail for new messages

I want to check my new Gmail messages periodically. When I get a message from a specific sender (with a specific Subject), I want to trigger some action. How to do that?

Fortunately, there is an atom feed of unread Gmail messages at https://mail.google.com/mail/feed/atom. All you have to do it is visit this page, send your login credentials, fetch the feed and process it.

import urllib2

FEED_URL = 'https://mail.google.com/mail/feed/atom'

def get_unread_msgs(user, passwd):
    auth_handler = urllib2.HTTPBasicAuthHandler()
        realm='New mail feed',
    opener = urllib2.build_opener(auth_handler)
    feed = urllib2.urlopen(FEED_URL)
    return feed.read()


if __name__ == "__main__":
    import getpass

    user = raw_input('Username: ')
    passwd = getpass.getpass('Password: ')
    print get_unread_msgs(user, passwd)

For reading XML I use the untangle module:

import untangle    # sudo pip install untangle

xml = get_unread_msgs(USER, PASSWORD)
o = untangle.parse(xml)
    for e in o.feed.entry:
        title = e.title.cdata
        print title
except IndexError:
    pass    # no new mail


Categories: python Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: