So I'm writing a program in Python that will traverse an Excel spreadsheet, get a PO number from it, and search our orders email account for that PO number. The problem is, when I print the number of results returned by the AdvancedSearch() method, it's usually zero (but not always - it's inconsistent).
I researched the problem a little and it looks like I need to handle the results using the AdvancedSearchComplete event. (I'm assuming the search usually doesn't find results before I try to print them in my code and that's why it's inconsistent.) I've tried to set up my code similarly to the code in this page: https://www.add-in-express.com/creating-addins-blog/2012/05/31/outlook-search-csharp-vbnet/, but it looks like the AdvancedSearchComplete event is handled automatically by the event handler in C# and VB.NET but not in Python. How can I handle this event in Python?
import win32com
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
folders = namespace.Folders("orders@company.com")
def advanced_search(po, folders, outlook):
scope = "'" + folders.Folders("Inbox").FolderPath + "','" + folders.Folders("Sent Items").FolderPath + "'"
filter = "urn:schemas:httpmail:textdescription LIKE '%" + po + "%' OR urn:schemas:mailheader:subject LIKE '%" + po + "%'"
search_subfolders = True
tag = "This is a search"
search = outlook.AdvancedSearch(scope, filter, search_subfolders, tag)
print(search.Results.Count)
def Application_AdvancedSearchComplete(search):
print("Advanced search completed")
EDIT: One suggestion I found was that the AdvancedSearchComplete event won't trigger if any code is being run after AdvancedSearch() is called. I tried removing the print statement in advanced_search() but that didn't change anything.