Outlook via COM via multi-thread in python

2019-08-17 12:17发布

问题:

I need to have couple threads operate on outlook (very lengthy explanation of why...). For example 1st thread would erase messages in one folder, another thread would do some filtering in elsewhere.

I understand I need to tap into outlook via COM and more in particularly via win32client and pythoncom. However I can not seem to marshall threads correctly. The basic setup that I have is this:

import win32com.client
import pythoncom

olApp = win32com.client.Dispatch('Outlook.Application')

myStream = pythoncom.CreateStreamOnHGlobal()

marshalledOlApp = pythoncom.CoMarshalInterface(
    myStream,
    pythoncom.IID_IDispatch,
    olApp,
    pythoncom.MSHCTX_INPROC,
    pythoncom.MSHLFLAGS_NORMAL
)

def cleanOutlook(marshalledOlApp):
  print 'How can I make outlook COM object be available here?'

  olApp = win32com.client.Dispatch(
        pythoncom.CoGetInterfaceAndReleaseStream(
            marshalledOlApp,
            pythoncom.IID_IDispatch))

threads = [threading.Thread(target=cleanOutlook, args=(marshalledOlApp,)) for _ in range(2)]

_ = [thread.start() for thread in threads]
_ = [thread.join() for thread in threads]

When I execute the .CoMarshalInterface(), I get an error message
ValueError: argument is not a COM object (got type=instance)

I looked through the APIs and googled my problem but can not seem to find a solution. Anyone knows how to have many threads tap into an Outlook?