Skip to content Skip to sidebar Skip to footer

Check Unread Count Of Gmail Messages With Python

How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.

Solution 1:

import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')

Solution 2:

Well, I'm going to go ahead and spell out an imaplib solution as Cletus suggested. I don't see why people feel the need to use gmail.py or Atom for this. This kind of thing is what IMAP was designed for. Gmail.py is particularly egregious as it actually parses Gmail's HTML. That may be necessary for some things, but not to get a message count!

import imaplib, reconn= imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login(username, password)
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)

Pre-compiling the regex may improve performance slightly.

Solution 3:

I advise you to use Gmail atom feed

It is as simple as this:

import urllib

url = 'https://mail.google.com/mail/feed/atom/'
opener = urllib.FancyURLopener()
f = opener.open(url)
feed = f.read()

You can then use the feed parse function in this nice article: Check Gmail the pythonic way

Solution 4:

For a complete implementation of reading the value from the atom feed:

import urllib2
import base64
from xml.dom.minidom import parse

defgmail_unread_count(user, password):
    """
        Takes a Gmail user name and password and returns the unread
        messages count as an integer.
    """# Build the authentication string
    b64auth = base64.encodestring("%s:%s" % (user, password))
    auth = "Basic " + b64auth

    # Build the request
    req = urllib2.Request("https://mail.google.com/mail/feed/atom/")
    req.add_header("Authorization", auth)
    handle = urllib2.urlopen(req)

    # Build an XML dom tree of the feed
    dom = parse(handle)
    handle.close()

    # Get the "fullcount" xml object
    count_obj = dom.getElementsByTagName("fullcount")[0]
    # get its text and convert it to an integerreturnint(count_obj.firstChild.wholeText)

Solution 5:

Well it isn't a code snippet but I imagine using imaplib and the Gmail IMAP instructions get you most of the way there.

Post a Comment for "Check Unread Count Of Gmail Messages With Python"