Create a Generator to read email and process messages

Viewed 159

I am trying to write some code to read my inbox and process some attachments if present. I decided this would be a good time to learn how generators work as I want to process all messages that have a particular subject. I have gotten to the point where I can get all the attachments and relevant subjects but I sort of had to fake it as the iterator in the for i in range . . . was not advancing so I am advancing the latest_email_id in the loop

def read_email_from_gmail():
    try:
        print 'got here'
        mail = imaplib.IMAP4_SSL(SMTP_SERVER)
        mail.login(FROM_EMAIL,FROM_PWD)
        mail.select('inbox')

        type, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()   
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])
        print latest_email_id


        while True:
            for i in range(latest_email_id,first_email_id - 1, -1):
                latest_email_id -= 1
                #do stuff to get attachment and subject
                yield attachment_data, subject


    except Exception, e:
        print str(e)

for attachment, subject in read_email_from_gmail():
    x = process_attachment(attachment)
    y = process_subject(subject)

Is there a more pythonic way to advance through my in-box using a generator to hold state in the in-box?

1 Answers
Related