#!/usr/bin/python
import imaplib, time, email.utils, email.parser, calendar


class EmailParser:
    def __init__(self, server, username, password, port=None, use_ssl=False, last_check=time.time()):
        self.server = server
        if not port:
            if use_ssl: self.port = 993
            else: self.port = 110
        else:
            self.port = port
        if use_ssl: self.imap = imaplib.IMAP4_SSL(self.server, self.port)
        else: self.imap = imaplib.IMAP4_SSL(self.server, self.port)
        self.imap.login(username, password)
        self.last_check = last_check
    def check(self):
        """
        Check for messages received since the last check.
        Return the number of unread messages.
        """
        folders = map(lambda x: x.split(' ')[2].strip('"'), self.imap.list()[1])
        notifications = []
        for folder in folders:
            if "[Gmail]" in folder: continue
            if self.imap.select(folder, True)[0] == "NO": continue # open read-only
            response, unseen = self.imap.search(None, 'UNSEEN')
            indices = unseen[0].split()
            nmessages = len(indices)
            i = nmessages - 1
            
            while i >= 0:
                # Fetch the received date and remove the preceding 'Date: '
                rfc2822 = self.imap.fetch(indices[i], '(BODY[HEADER.FIELDS (DATE)])')[1][0][1][6:]
                time_received = time.mktime(email.utils.parsedate(rfc2822))
                if time_received + 10 * 60 < self.last_check:
                    break
                sender = self.imap.fetch(indices[i], '(BODY[HEADER.FIELDS (FROM)])')[1][0][1][6:-4]
                subject = self.imap.fetch(indices[i], '(BODY[HEADER.FIELDS (SUBJECT)])')[1][0][1][9:-4]
                notifications.append({"sender" : sender, "subject" : subject})
                i -= 1
        self.last_check = time.time()
        return notifications

@@ -581,16 +581,556 @@
 st_check
+%0A%0A    def is_new(self, mail_string):%0A        %22%22%22 Takes a string of the form%0A        %0A        Date: Sun, 17 Jan 2010 00:59:10 -0500 (EST)%0A        From: John Doe %3Canyman@example.com%3E%0A        Subject: TPS reports%0A%0A        and returns whether that e-mail was received since last check.%0A        %22%22%22%0A        date_header = get_field(%22Date%22, mail_string)%0A        date_tuple = email.utils.parsedate_tz(date_header)%0A        time_received = calendar.timegm(date_tuple%5B0:8%5D) - date_tuple%5B9%5D%0A        return time_received %3E self.last_check%0A    %0A%0A        
 %0A    def
@@ -1714,21 +1714,8 @@
 - 1%0A
-            %0A
     
@@ -2419,16 +2419,16 @@
 .time()%0A
-
         
@@ -2448,8 +2448,280 @@
 cations%0A
+%0Adef get_field(name, field_string):%0A    fields = filter(lambda x: x.startswith(name.capitalize() + %22:%22), field_string.split(%22%5Cr%5Cn%22))%0A    if fields == %5B%5D: return None%0A    else: return fields%5B0%5D.lstrip(name.capitalize() + %22: %22)            %0A                %0A                %0A

add an is_new function to check newness of messages; hopefully it deals with timezones properly