Context : I have 100 emails with the a subject as 'Target subject <something>'
in my Oulook inbox and I want to move them all in an other folder, let's say 'MyFolder'
. Here is my python (version=3.9.6) program :
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
root_folder = outlook.Folders.Item(1)
inbox = outlook.GetDefaultFolder(6)
myfolder = root_folder.Folders['MyFolder']
messages = inbox.Items
for message in messages:
if 'Target subject' in message.Subject:
message.Move(myfolder)
Problem: The program runs without throwing any error but only 20 emails of 100 expected are moved. If I run the program several times, it achieved to move all like 20 at a time.
Attempts: I've searched in windows API documentation but found nothing useful.
Question : Any idea of what's causing this limitation and how to avoid it?
Thanks !
First of all, I have noticed the following lines of code:
for message in messages:
if 'Target subject' in message.Subject:
That is really not a good idea to iterate over all items in the folder and check whether a subject line contains specific keywords. Instead, I'd recommend using the Find/FindNext or Restrict methods of the Items
class. Read more about these methods in the following articles:
If you still deal with a collection of items (in the case of Restrict
method) you need to iterate through all items using the for
loop from the end and call the Move
method in the following way:
for i in reversed(messages):
i.Move(myFolder)