简体   繁体   中英

For loop exits while downloading outlook email attachments python

I have developed a code to iterate over outlook folder and download attachment from emails that have a predefined subject line and delete the message and delete messages that have a different subject than the predefined one.the code is as below

folder = inbox.Folders("folder")
for msg in folder.Items:
    if msg.Subject == "Predefined msg Subject":
        for att in msg.Attachments:
            msg_date = msg.SentOn.srftime(%Y-%m-%d)
            att.SaveAsFile(os.path.join(dest_folder, msg_date + "_" + att.Filename)
    else:
        pass
    msg.Delete()
    continue

I have about 150 messages in the folder, there are about 8 messages with required attachments and others are just to bedeleted. but the loop above breaks at 73 exactly (i used a counter and msg.Subject to where it breaks and why). The sencond run then breaks after ~24 and so forth. I had to run the code 3 more times to go over all the emails from folder. Any idea why the code exits loop

Your code is modifying the collection it is iterating over. Instead of using a "for" loop use a loop from items.Count down to 1.

As a side note, iterating through all messages in a folder is a horrible idea - use Items.Restrict or Items.Find/FindNext to let the message store find the matches for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM