Home > Programming > Simple check if you have new mail in Gmail

Simple check if you have new mail in Gmail

This is a simple illustration of how you can use the python imaplib to check mail. This is really simple for experienced python programmers, but not for new ones. This can be made use of in several ways. For example I dislike the N900 mail client, I use this script to quickly check if I have new mail.
Here is the code illustration.

class MailMessagePreview:
    def __init__(self):
        self.date=None
        self.subject=None
        self.emailFrom=None

class SecureInboxMail(imaplib.IMAP4_SSL, object):
    def __init__(self, serverHostAddress, serverPort, userName, passWord):
        self.__isLoggedIn=False
        super(SecureInboxMail, self).__init__(serverHostAddress, serverPort)
        self.open(serverHostAddress, serverPort)
        self.login(userName,passWord)
        self.__isLoggedIn=True
        self.__mailFolders=None

    def getMailFolders(self):
        if not(self.__mailFolders):
            resp = self.list()
            if(resp[0]=="OK"):
                self.__mailFolders = self.__parseFolders(resp[1])
        return self.__mailFolders

    def __parseFolders(self, folderList):
        return [ re.search('\((.*)\) "(.*)" "(.*)"', folder).group(3) for folder in folderList ]

    def getFolderNewMail(self, folderName='INBOX'):
        self.select(folderName)
        # reference section used http://tools.ietf.org/rfc/rfc2060.txt fetch command
        return [ self.__passMailPeekResponse(self.fetch(unreadMailIndex, "(BODY.PEEK[HEADER.FIELDS (DATE FROM SUBJECT)])")) for unreadMailIndex in  (self.search(None,'UNSEEN')[1][0]).split()]

    def __passMailPeekResponse(self, mailResponse):
        if(mailResponse[0]=='OK'):
            mailMessagePreview=MailMessagePreview()
            mailMessagePreview.date=re.search("Date:(.*)\\s", str(mailResponse[1][0][1])).group(1).strip()
            mailMessagePreview.emailFrom=re.search("From:(.*)\\s", str(mailResponse[1][0][1])).group(1).strip()
            mailMessagePreview.subject=re.search("Subject:(.*)\\s", str(mailResponse[1][0][1])).group(1).strip()
            return mailMessagePreview

    def getUnreadMessageCount(self, folderName='INBOX'):
        self.select(folderName)
        return re.search("\(UNSEEN (\d+)\)", self.status(folderName, "(UNSEEN)")[1][0]).group(1)

class GmailInboxMail(SecureInboxMail):
    def __init__(self,userName, passWord, serverHostAddress='imap.gmail.com', serverPort=993):
        super(GmailInboxMail, self).__init__(serverHostAddress, serverPort, userName, passWord)

    def getLabels(self):
        return self.getMailFolders();

and to make use of the classes

try:
    userName = raw_input('Enter username: ').strip()
    passWord = raw_input('Enter password: ').strip()

    if(len(userName) == 0 or len(passWord) == 0):
        print "Both username and password required"
        return                

    gmailMaildir = GmailInboxMail(userName, passWord)
    print "\nFolders: " + ", ".join(gmailMaildir.getMailFolders())
    print "\nInbox Unread Messages " + str(gmailMaildir.getUnreadMessageCount())
    print "\nMessages:"
    for x in  gmailMaildir.getFolderNewMail():
        print str.rjust(x.date,2), str.rjust(x.emailFrom,3), str.rjust(x.subject,4)
    gmailMaildir.close()
    gmailMaildir.logout()
except Exception, (instance):
    print str(instance)
Advertisements
Categories: Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

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: