Check unread count of Gmail messages with Python Check unread count of Gmail messages with Python python python

Check unread count of Gmail messages with Python


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


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.


I advise you to use Gmail atom feed

It is as simple as this:

import urlliburl = '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