3

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.

ʇsәɹoɈ
  • 22,757
  • 7
  • 55
  • 61
kettlepot
  • 10,574
  • 28
  • 71
  • 100

4 Answers4

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
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
4

Take a look at the python standard library's POP3 and IMAP packages.

ʇsәɹoɈ
  • 22,757
  • 7
  • 55
  • 61
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