Search code examples
pythonoutlookpywin32win32comoffice-automation

Outlook unread email loop stops prematurely


I have the following code, it runs correctly however if there are more than a couple of emails with attachments in the folder, it will process 2 and then stop the loop. Any ideas?

for email in unread_emails:
    if email.Attachments.Count > 0:
        for attachment in email.Attachments:
            subject = email.Subject
 
            if attachment.FileName.endswith('.xls') or attachment.FileName.endswith('.xlsx'):
                Vendor_Name_Raw = email.subject
                Vendor_Name = Vendor_Name_Raw.split(Split_Word)[0]
                Cleaned_FileName = (Vendor_Name + " " + attachment.FileName)
                attachment.SaveAsFile(os.path.join(save_folder, Cleaned_FileName))
            email.UnRead = False

Basically the script will download the xlsx file attached to the email, rename it and save it to the relevant folder. It'll work the first couple of iterations however it will eventually stop. I tried implementing a 3 second sleep into the script but it didn't help. The folder is a onedrive folder if that makes any difference?


Solution

  • If unread_emails comes from Items.Restrict, keep in mind that by setting email.UnRead = False you are modifying the collection as you are iterating over it. Do not do that.

    Loop from Count down to 1 instead of using a for loop:

    for i in range(unread_emails.Count, 0, -1):
      email = unread_emails.Item(i)