Search code examples
pythonsmtpimap

IndexError using stmplib in Python


I am trying to forward out and delete certain emails from a gmail account and run the others through a separate process. I've been following this example but for some reason I am running into an IndexError that my try catch I included up for another issue (if the inbox is empty) picks up.

# 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)

I can't seem to figure out why I'm receiving this error. Any insight would be greatly appreciated.


Solution

  • You need to indent the

    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'
    

    If you don't, then res_part won't be a variable.