Iterate Though Messages from Inbox and Specific Subfolder with win32com

62 Views Asked by At

Can anyone tell me how I might be able to assemble an object that contains mail items from after a specific date from both my inbox and a specified folder of my inbox? I know how to get the items from each one separately, but I'm not sure how to combine them.

This is necessary due to the existence of an Outlook rule that moves messages to the folder, but it can only run when Outlook is open. Typically, the messages I need are in the folder, but if the rule hasn't run, I need to pick up messages from the general inbox too.

Here is what I have so far:

import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
root =outlook.Folders.Item(1).Folders('Inbox')

msg_fromdate= '09/03/2023'
filter_time = "[ReceivedTime]>="+"'"+msg_fromdate+" 12:00 AM" +"'"

inbox_messages = root.Items.Restrict(f'{filter_time}')
folder_messages = root.Folders('folder_name').Items.Restrict(f'{filter_time})

I need to iterate from message from both of these objects, but it would be easier to merge them into a single iterable object if that's possible.

Anyone have an idea?

2

There are 2 best solutions below

1
On

You cannot do that - Outlook is not a relational database, you cannot create a join from two folders.

Nothing, however, prevents you from creating an array with the length equal to the sum of two collections and populating that array/list with items from two collections.

0
On

You need to use the AdvancedSearch method of the Application class which allows getting items from multiple folders. The key benefits of using the AdvancedSearch method in Outlook are:

  • The search is performed in another thread. You don’t need to run another thread manually since the AdvancedSearch method runs it automatically in the background.
  • Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).
  • Full support for DASL queries (custom properties can be used for searching too). To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).
  • You can stop the search process at any moment using the Stop method of the Search class.

Read more about that in the article that I wrote for the technical blog more than a decade ago - Advanced search in Outlook programmatically: C#, VB.NET.