创建生成器以阅读电子邮件并处理消息

时间:2017-11-25 16:27:59

标签: python python-2.7 email generator

我正在尝试编写一些代码来读取我的收件箱并处理一些附件(如果存在)。我决定这是学习生成器如何工作的好时机,因为我想处理所有具有特定主题的消息。我已经到了可以获得所有附件和相关主题的地步但我不得不伪造它,因为for i in range . . .中的迭代器没有前进所以我在循环中推进latest_email_id

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)

是否有更多的pythonic方式通过我的收件箱使用发生器在收件箱中保持状态?

1 个答案:

答案 0 :(得分:0)

我已经学习了很多关于生成器的知识并且使用了我开始使用的代码,所以我有一个函数使用生成器来发送主要功能的每个相关电子邮件消息。这是我到目前为止所做的,它非常适合我的需求

import imaplib
import email
FROM_EMAIL  = 'myemail@gmail.com'
FROM_PWD    = "mygmail_password"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT   = 993
STOP_MESSAGES = set(['Could not connect to mailbox',
                     'No Messages or None Retrieved Successfully',
                     'Could not retrieve some message',
                     'Finished processing'])

def  read_emails():
    mail = imaplib.IMAP4_SSL(SMTP_SERVER)
    mail.login(FROM_EMAIL,FROM_PWD)
    mail.select('inbox')
    con_status, data = mail.uid('search', None, "ALL")
    if con_status != 'OK':
        yield 'Could not connect to mailbox'
    try:
        mail_ids = data[0].split()
    except Exception:
        yield 'No Messages or None Retrieved Successfully'
    print mail_ids

    processed = []
    while True:
        for mail_id in mail_ids:
            status, mdata = mail.uid('fetch', mail_id, '(RFC822)')
            if status != 'OK':
                yield 'Could not retrieve some message'
            if mail_id in processed:
                yield 'Finished processing'
            raw_msg = mdata[0][1]
            structured_msg = email.message_from_string(raw_msg)
            msg_subject = structured_msg['subject']
            processed.append(mail_id)
            yield msg_subject

要逐个访问我的消息,我然后使用以下块来获取消息

for msg_subj in read_emails():
    if msg_subj not in STOP_MESSAGES:
         do some stuff here with msg_subj
    else:
        print msg_subj
        break

我正在通过uid访问这些邮件,因为我稍后会将其删除,并希望使用uid作为管理删除的密钥。对我而言,诀窍是收集名为uid的列表中的processed,然后检查我是否会再次绕过它们,因为我正在使用已经已经uid的{​​{1}}已被处理。