#!/usr/bin/env python

import sys
import imaplib
import getpass
import email
import email.header
import datetime

EmailAccount = "rzzzwilson@gmail.com"
EmailBox = "INBOX"

InitialNumber = 20
MBPrefix = '(\\HasNoChildren) "/" "'


def get_email_header(M, num, data):
    """Get an email header display string.

    M     the mail server object
    num   unique ID of email message
    data  data returned from a select()

    Returns a tuple (subject, datetime).
    """

    msg = email.message_from_string(data[0][1])
    decode = email.header.decode_header(msg['Subject'])[0]
    try:
        subject = unicode(decode[0])
    except UnicodeDecodeError as e:
        if 'ordinal not in range' in e.reason:
            # looks like subject is already unicode?
            subject = decode[0]
        else:
            raise

    # Now convert to local date-time
    date_tuple = email.utils.parsedate_tz(msg['Date'])
    local_time = None
    if date_tuple:
        local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))

    # remove extraneous stuff in subject
    ndx = subject.find('\n')
    if ndx >= 0:
        subject = subject[:ndx]
#    subject = subject.replace('\r', '')

    return (subject, local_date)

def process_mailbox(M):
    """
    Do something with emails messages in the folder.
    For the sake of this example, print some headers.
    """

    (rv, data) = M.search(None, "ALL")
    if rv != 'OK':
        print "No messages found!"
        return

    ids = data[0].split()[-InitialNumber:]
    ids.reverse()

    for num in ids:
        (rv, data) = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print('ERROR getting message %d' % num)
            return
        (subject, time) = get_email_header(M, num, data)
        local_time = time.strftime('%a, %d %b %Y %H:%M:%S')
        print('Email %s:%s\t%s' % (num, subject, time))


M = imaplib.IMAP4_SSL('imap.gmail.com')

try:
    (rv, data) = M.login(EmailAccount, getpass.getpass())
except imaplib.IMAP4.error:
    print('LOGIN FAILED!!!')
    sys.exit(1)

(rv, mailboxes) = M.list()
if rv == 'OK':
    print "Mailboxes:"
    for mb in mailboxes:
        if mb.startswith(MBPrefix):
            mb_name = mb[len(MBPrefix):-1]
            print('mb=%s, mb_name=%s' % (str(mb), mb_name))
    #print mailboxes

(rv, data) = M.select(EmailBox)
if rv == 'OK':
    print('Processing mailbox %s' % EmailBox)
    process_mailbox(M)
    M.close()
else:
    print "ERROR: Unable to open mailbox ", rv

M.logout()

@@ -14,16 +14,17 @@
 v python
+3
 %0A%0Aimport
@@ -108,16 +108,79 @@
 tetime%0A%0A
+import logger%0Alog = logger.Log('test.log', logger.Log.DEBUG)%0A%0A%0A
 EmailAcc
@@ -186,17 +186,18 @@
 count = 
-%22
+u'
 rzzzwils
@@ -208,17 +208,17 @@
 mail.com
-%22
+'
 %0AEmailBo
@@ -225,15 +225,16 @@
 x = 
-%22
+u'
 INBOX
-%22
+'
 %0A%0AIn
@@ -261,16 +261,22 @@
 refix = 
+bytes(
 '(%5C%5CHasN
@@ -292,16 +292,26 @@
 ) %22/%22 %22'
+, 'utf-8')
 %0A%0A%0Adef g
@@ -542,24 +542,57 @@
 ).%0A    %22%22%22%0A%0A
+    s = str(data%5B0%5D%5B1%5D, 'utf-8')%0A
     msg = em
@@ -615,26 +615,17 @@
 _string(
-data%5B0%5D%5B1%5D
+s
 )%0A    de
@@ -681,21 +681,8 @@
 %5B0%5D%0A
-    try:%0A    
     
@@ -695,16 +695,8 @@
 t = 
-unicode(
 deco
@@ -704,209 +704,8 @@
 e%5B0%5D
-)%0A    except UnicodeDecodeError as e:%0A        if 'ordinal not in range' in e.reason:%0A            # looks like subject is already unicode?%0A            subject = decode%5B0%5D%0A        else:%0A            raise
 %0A%0A  
@@ -972,22 +972,16 @@
 %0A   
- ndx =
  subject
 .fin
@@ -980,70 +980,38 @@
 ject
-.find('%5Cn')%0A    if ndx %3E= 0:%0A        subject = subject%5B:ndx%5D%0A#
+ = subject.replace('%5Cn', ' ')%0A
     
@@ -1039,16 +1039,17 @@
 lace('%5Cr
+ 
 ', '')%0A%0A
@@ -1301,18 +1301,18 @@
    print
- %22
+('
 No messa
@@ -1321,17 +1321,18 @@
 s found!
-%22
+')
 %0A       
@@ -1701,17 +1701,19 @@
 'Email %25
-s
+04d
 :%25s%5Ct%25s'
@@ -1715,20 +1715,25 @@
 %5Ct%25s' %25 
+(int
 (num
+)
 , subjec
@@ -1973,18 +1973,18 @@
    print
- %22
+('
 Mailboxe
@@ -1985,17 +1985,18 @@
 ilboxes:
-%22
+')
 %0A    for
@@ -2013,16 +2013,69 @@
 lboxes:%0A
+        print('mb=%25s, type(mb)=%25s' %25 (mb, type(mb)))%0A
         
@@ -2372,18 +2372,18 @@
    print
- %22
+('
 ERROR: U
@@ -2407,14 +2407,18 @@
 lbox
- %22
+: %25s'
 , rv
+)
 %0A%0AM.

Convert to run under python 3