I am running the below code it works like a charm for few days and now I am facing the following error message: "list index out of range" related to:
for i in range(item_count, 0, -1):
message = out_iter_folder.Items[i]
this code was running perfectly for weeks and I can fix it just by replacing the calculated item_count value with the same one -1 not really sure why it worked and stopped working ?
many thanks :) !
import win32com.client
EMAIL_ACCOUNT = 'Enter your email address' # e.g. '[email protected]'
ITER_FOLDER = 'Enter the Outlook folder name which emails you would like to iterate through' # e.g.
'IterationFolder'
MOVE_TO_FOLDER = 'Enter the Outlook folder name where you move the processed emails' # e.g
'ProcessedFolder'
SAVE_AS_PATH = 'Enter the path where to dowload attachments' # e.g.r'C:\DownloadedCSV'
EMAIL_SUBJ_SEARCH_STRING = 'Enter the sub-string to search in the email subject' # e.g. 'Email to
download'
def find_download_csv_in_outlook():
out_app = win32com.client.gencache.EnsureDispatch("Outlook.Application")
out_namespace = out_app.GetNamespace("MAPI")
out_iter_folder = out_namespace.Folders[EMAIL_ACCOUNT].Folders[ITER_FOLDER]
out_move_to_folder = out_namespace.Folders[EMAIL_ACCOUNT].Folders[MOVE_TO_FOLDER]
char_length_of_search_substring = len(EMAIL_SUBJ_SEARCH_STRING)
# Count all items in the sub-folder
item_count = out_iter_folder.Items.Count
if out_iter_folder.Items.Count > 0:
for i in range(item_count, 0, -1):
message = out_iter_folder.Items[i]
# Find only mail items and report, note, meeting etc items
if '_MailItem' in str(type(message)):
print(type(message))
if message.Subject[0:char_length_of_search_substring] == EMAIL_SUBJ_SEARCH_STRING \
and message.Attachments.Count > 0:
for attachment in message.Attachments:
if attachment.FileName[-3:] == 'csv':
attachment.SaveAsFile(SAVE_AS_PATH + '\\' + attachment.FileName)
message.Move(out_move_to_folder)
else:
print("No items found in: {}".format(ITER_FOLDER))
if __name__ == '__main__':
find_download_csv_in_outlook()
khelwood
59.7k14 gold badges91 silver badges116 bronze badges
1 Answer 1
The range will go from item_count(included) to 0(excluded). So, you have to loop it from item_count-1 to -1 as the indexing of the list starts from 0 not 1.
for i in range(item_count-1, -1, -1):
message = out_iter_folder.Items[i]
OR
for i in reversed(range(0,item_count)):
message = out_iter_folder.Items[i]
answered May 21, 2021 at 17:03
Binary Phoenix
811 silver badge5 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
4has indices0,1,2, and3. You need to iterate fromlen(list) - 1to zero (both inclusive), so you need to dorange(len(list) - 1, -1, -1). See this similar recent question: stackoverflow.com/q/67593572/843953range(5, 0, -1)starts at5and ends at1and it is very likely thatout_iter_folder.Items[i]is out of range on the first iteration since lists are0-basedand would expect indexes starting at4and ending at0.