is there any way, in Python, to have access to an e-mail account (I'll need this for gmail but better if any works) and be able to see the number of messages in the inbox (maybe even unread messages only)? Thank you.
Asked
Active
Viewed 1.3k times
4 Answers
6
Try
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('Inbox') <-- it will return total number of mail in Inbox i.e
('OK', ['50'])
obj.search(None,'UnSeen') <-- it will return the list of uids for Unseen mails

General Grievance
- 4,555
- 31
- 31
- 45

Avadhesh
- 4,519
- 5
- 33
- 44
-
hey .. this is not outputting any result .. have the libs changed since this ? – ScipioAfricanus Apr 12 '18 at 22:00
4
Building on Avadhesh's answer:
#! /usr/bin/env python3.4
import getpass
import imaplib
mail = imaplib.IMAP4_SSL('imap.server.com')
mypassword = getpass.getpass("Password: ")
address = 'your@email.com'
mail.login(address, mypassword)
mail.select("inbox")
print("Checking for new e-mails for ",address,".", sep='')
typ, messageIDs = mail.search(None, "UNSEEN")
messageIDsString = str( messageIDs[0], encoding='utf8' )
listOfSplitStrings = messageIDsString.split(" ")
if len(listOfSplitStrings) == 0:
print("You have no new e-mails.")
elif len(listOfSplitStrings) == 1:
print("You have",len(listOfSplitStrings),"new e-mail.")
else:
print("You have",len(listOfSplitStrings),"new e-mails.")
-
hi, your answer really helped me a lot. im a total newbie on imaplib and im trying to get the 20 most recent email on our imap server. can you help me on how i would do that? – hocuspocus31 Aug 15 '16 at 23:38
1
An alternate gmail specific solution for finding unread messages:
Gmail offers atom feeds for messages. For example:
https://mail.google.com/mail/feed/atom/ (unread messages in inbox) http://mail.google.com/mail/feed/atom/labelname/ (unread messages in labelname) http://mail.google.com/mail/feed/atom/unread/ (all unread messages)
So you could use the excellent feedparser library to grab the feed and count the entries.
Now that I'm looking at it, though, it appears that the unread messages feed only returns up to 20 entries, so this might be a bit limited.

fitzgeraldsteele
- 4,547
- 3
- 24
- 25