2017-11-25 252 views
2

我尝试写一些代码来阅读我的收件箱,如果现在处理一些附件。我决定这将是学习生成器如何工作的好时机,因为我想处理所有具有特定主题的消息。我得到的地步,我可以得到所有的附件和相关科目,但我有点不得不伪造其作为for i in range . . .迭代器并没有前进,所以我在循环创建一个发电机来阅读电子邮件和处理消息

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) 

是推进latest_email_id还有更多的pythonic方法可以通过我的收件箱使用发电机在收件箱中保持状态?

+0

你可能想你的代码比较[E-SATIS'(https://stackoverflow.com/a/642988/190597)。他显示了一种不同的方式来遍历消息,而不需要'for i in range(...)'循环。 – unutbu

+0

我开始用这种方法,然后想知道一台发电机,所以我可以封装代码更好 - 其他的东西我必须做的每封电子邮件是非常广泛,就像我说的,我懒懒地想知道如何使用发电机 – PyNEwbie

回答

0

我已经学到了一些关于发电机和与我开始与代码发挥各地,所以我有一个使用发电机来发送各相关电子邮件主题为主要功能的功能。这是我迄今为止,它对于我的需求

import imaplib 
import email 
FROM_EMAIL = '[email protected]' 
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为重点,以管理缺失。对我来说,诀窍是收集在一个名为processed列表中的uid,然后检查,看看是否我正想再通过他们来圈,因为我与已经处理的uid工作。