0

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.

1 Answers1

0

You need to subscribe to the AdvancedSearchComplete of the Application class (which is outlook in your code). Simply pasting the event handler will not be working out of the box.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • How would I do that? Every solution I've looked at responds to an event using a class (I think), but I just want to run a function when the event has occurred. – Parker Piedmont Jun 26 '19 at 19:13
  • Sorry, but I am far away from Python. You may take a look at https://stackoverflow.com/questions/1092531/event-system-in-python – Eugene Astafiev Jun 26 '19 at 22:42