Home > Software design >  Repeating code execution or alternative: Python, Outlook
Repeating code execution or alternative: Python, Outlook

Time:06-08

I have an issue with the execution quality with the below code when trying to move emails from inbox to another folder.

inbox = inbox.Items
example_folder = inbox.Restrict("[SenderEmailAddress] = '[email protected]'")
for message in example_folder:
    message.Move(folder)

The problem is not every email will move when commanded, same happens for SenderName, Subject, and others so it's not what I'm extracting the emails by. It does work, but I need to keep executing it to catch the ones it missed. Any suggestions to the code? If not, is there a way for me to add new code that just repeats the command automatically until i want it to stop? (once all emails have been moved).

Thanks

CodePudding user response:

First of all, I'd recommend using the reversed for loop instead, see Backward iteration in Python for more information on that.

Second, I'd suggest checking whether all the required items are found using the Restrict method. Your collection may not contain all items you expect to be moved to the folder. So, it makes sense to run the code under the debugger and compare how many items are found and moved to the folder.

CodePudding user response:

You are modifying (by calling Move) the very collection you are iterating over, this can result in some items being skipped. Use a backward for loop from Items.Count down to 1.

  • Related