在Python

时间:2017-05-13 04:37:54

标签: python smtp imap

我正在尝试转发并从Gmail帐户中删除某些电子邮件,并通过单独的流程运行其他电子邮件。我一直在关注this example,但由于某种原因,我遇到IndexError try我的另一个问题(如果收件箱为空)选择catch起来。

# Connect and login to email
imap = imaplib.IMAP4_SSL('imap.gmail.com')
imap.login('sender','password')
imap.list()
imap.select('inbox')

smtp = smtplib.SMTP_SSL('smtp.gmail.com')
smtp.login('sender','password')

try:
    result, data = imap.search(None,'ALL') # search and return sequential ids
    ids_list = data[0].split()
    print 'Total emails: '+str(len(ids_list))
    latest_id = ids_list[-1]

    #Process each email in inbox
    for i in ids_list:
        t, d = imap.fetch(i, '(RFC822)')
        for res_part in d:
            if isinstance(res_part, tuple):
                msg = email.message_from_string(res_part[1])
                subject = msg['subject']
                print 'Subject: '+subject
        if subject != 'Subject of email I care about':
            print 'Dealing with it'
            #Forward email to another account
            #Attempt to forward an email
            text = res_part[0][1] #Something is wrong with this line, throws exception
            smtp.sendmail('sender', 'destination', text)
            imap.store(i, '+FLAGS', '\\Deleted')
            imap.expunge()
        else:
            #Process email
            print 'Don\'t delete this'

except IndexError:
    print 'Error'
    #Inbox is empty (Or in this case apparently not)

我似乎无法弄清楚为什么我收到此错误。任何见解将不胜感激。

2 个答案:

答案 0 :(得分:1)

你需要缩进

if subject != 'Subject of email I care about':
            print 'Dealing with it'
            #Forward email to another account
            #Attempt to forward an email
            text = res_part[0][1] #Something is wrong with this line, throws exception
            smtp.sendmail('sender', 'destination', text)
            imap.store(i, '+FLAGS', '\\Deleted')
            imap.expunge()
else:
            #Process email
            print 'Don\'t delete this'

如果不这样做,则res_part将不是变量。

答案 1 :(得分:0)

我认为你的缩进中有一个拼写错误,因为这不是你的问题。然而,你使用res_part犯了另一个错误。在您的代码中,您使用d作为元素循环遍历数据res_part。现在,这意味着res_part每次迭代只包含部分d。因此,它将具有较低的维度。你可能想要这样的东西:

# Connect and login to email
imap = imaplib.IMAP4_SSL('imap.gmail.com')
imap.login('sender','password')
imap.list()
imap.select('inbox')

smtp = smtplib.SMTP_SSL('smtp.gmail.com')
smtp.login('sender','password')

try:
    result, data = imap.search(None,'ALL') # search and return sequential ids
    ids_list = data[0].split()
    print 'Total emails: '+str(len(ids_list))
    latest_id = ids_list[-1]

    #Process each email in inbox
    for i in ids_list:
        t, d = imap.fetch(i, '(RFC822)')
        text = d[0][1]
        msg = email.message_from_string(text)
        subject = msg['subject']
        print 'Subject: '+subject
        if subject != 'Subject of email I care about':
            print 'Dealing with it'
            #Forward email to another account
            #Attempt to forward an email
            smtp.sendmail('sender', 'destination', text)
            imap.store(i, '+FLAGS', '\\Deleted')
            imap.expunge()
        else:
            #Process email
            print 'Don\'t delete this'

except IndexError:
    print 'Error'
    # Probably won't happen for empty inbox either, as for loop will not execute
    # To catch an empty inbox you could you an `else:` construct.
    #Inbox is empty (Or in this case apparently not)

我还没有测试过这段代码。特别是我假设您从数据部分获取消息的方式与您实现它的方式一致。此外,这不会测试d的第一个元素,即d[0]是一个元组。我假设,在您链接到的示例中假设了这一点。