IndexError 在 Python 中使用 stmplib

IndexError using stmplib in Python

我正在尝试从一个 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)

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

您需要缩进

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 将不是一个变量。

我认为您的缩进有错别字,因为那不是您遇到的问题。你犯了另一个错误,但是使用 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] 是一个元组。我假设,就像您链接到的示例中假设的那样。