import imaplib


def idle(connection):
    tag = connection._new_tag()
    connection.send("%s IDLE\r\n" % tag)
    response = connection.readline()
    connection.loop = True
    if response == '+ idling\r\n':
        while connection.loop:
            resp = connection.readline()
            uid, message = resp[2:-2].split(' ')
            yield uid, message
    else:
        raise Exception("IDLE not handled? : %s" % response)


def done(connection):
    connection.send("DONE\r\n")
    connection.loop = False

imaplib.IMAP4.idle = idle
imaplib.IMAP4.done = done

if __name__ == '__main__':
    import os
    import email
    user = os.environ['EMAIL']
    password = os.environ['PASSWORD']
    print os.environ['SERVER']
    m = imaplib.IMAP4_SSL(os.environ['SERVER'])
    m.login(user, password)
    m.select()
    loop = True
    while loop:
        for uid, msg in m.idle():
            print uid, msg
            if msg == "EXISTS":
                m.done()
                status, datas = m.fetch(uid, '(RFC822)')
                for raw_mail in datas:
                    mail = email.message_from_string(raw_mail[1])
                    for field, value in mail.items():
                        print field
                        print "\t", value

@@ -614,20 +614,43 @@
     
+from lamson.mail 
 import 
-em
+M
 ail
+Request
 %0A   
@@ -750,17 +750,20 @@
 R'%5D%0A    
-m
+conn
  = imapl
@@ -801,17 +801,20 @@
 '%5D)%0A    
-m
+conn
 .login(u
@@ -832,17 +832,20 @@
 rd)%0A    
-m
+conn
 .select(
@@ -902,17 +902,20 @@
  msg in 
-m
+conn
 .idle():
@@ -990,17 +990,20 @@
         
-m
+conn
 .done()%0A
@@ -1034,17 +1034,20 @@
 datas = 
-m
+conn
 .fetch(u
@@ -1082,92 +1082,57 @@
     
-for raw_mail in datas:%0A                    mail = email.message_from_string(raw_mail
+m = MailRequest('localhost', None, None, datas%5B0%5D
 %5B1%5D)
@@ -1152,54 +1152,23 @@
     
-   
- for field, value 
+pr
 in
+t
  m
-ail.items():%0A        
+.keys()%0A
     
@@ -1189,16 +1189,22 @@
 int 
-field%0A  
+m.all_parts()%0A
     
@@ -1219,28 +1219,24 @@
     
-      print %22%5Ct%22, value
+print m.is_bounce()
 %0A

Read mail with Lamson.