Search code examples
python-3.xoutlookimapclient

List Index be out of range in a for i in List loop using IMAPClient?


I'm not sure if I'm missing something obvious. I am trying to retrieve emails and iterate over them to find specific items in the text. The code runs but throws a 'List Index out of range' error part way through iterating over the items in the selected folder. I don't see how that can happen when the list being iterated over is a list of index positions to being with?

I am using the IMAPClient package, and my script selects the right folder, and finds emails with a specific subject then returns a list

client.select_folder('WebsiteMessages', readonly=True)
result = client.search('SUBJECT "User Details"')
print(result)

this returns a list of items in the folder that match the search criteria

 [1, 2, 9, 10, 11, 15, 19, 22, 23, 24, 25, 26, 27, 28, 30, 32, 36, 46, 48, 49, 51, 55, 57, 60, 61]

If I try to iterate over that list I get to a specific point and then get the list index out of range error.

for i in result:
    message = client.fetch(result[i], b'RFC822')
    print(message)

I don't understand how the error occurs seeing as the list is generated by the search? Any ideas?


Solution

  • Not tested, just a guess:

    for i in result:
        message = client.fetch(i, b'RFC822')
        print(message)
    

    i already is already the value, using it as an index for the value is incorrect.

    A second solution, which might be what you intended:

    for i in range(result):
        message = client.fetch(result[i], b'RFC822')
        print(message)