0

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?

JavaFan
  • 1,295
  • 3
  • 19
  • 28
  • 1
    As COMObject cannot be passed to a thread, you need to do a little bit more work, see: [https://stackoverflow.com/a/27966218/4121573](https://stackoverflow.com/a/27966218/4121573) – Adonis Dec 18 '18 at 09:56
  • Thanks, @Adonis. Your pointer definitely helped. Can I only pass COM programs (ie Excel, outlook, word, etc) or is it also possible to pass any objects (derived from COM programs) from thread to thread. I am in particular interested in passing a list of outlook MailItems to two different threads and have these threads process the list of mailitems independently basied on thread-specific logic – JavaFan Dec 18 '18 at 16:53
  • It seems that you still need a bit of initialization per thread ([https://msdn.microsoft.com/en-us/library/ms809971.aspx](https://msdn.microsoft.com/en-us/library/ms809971.aspx]), now I've not used COMObject in a multithreaded context, so I'd say you'll have to proceed by trial and error – Adonis Dec 19 '18 at 09:34
  • @Adonis, it turns out that every thread needs its own marshalled object. then all works. On a slightly diff note (not multi-threaded). When I am calling methods on an object lets say mailItem.Delete(), I get an attribute error .Delete. have you seen such errors by any chance? – JavaFan Dec 19 '18 at 15:19

0 Answers0