1

I am trying to automate outlook, using python Django. the code works pretty good directly using python, but when using it in my Django app it gives me this error.

> pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

and my views code is :

import win32com.client as win32
 def about(request):
    olApp = win32.Dispatch('Outlook.Application')
    olNS = olApp.GetNameSpace('MAPI')
    inbox = olNS.GetDefaultFolder(6)
    messages = inbox.Items
    for msg in messages:
           if msg.Class==43:
               if msg.SenderEmailType=='EX':
                   print(1,msg.Sender.GetExchangeUser().PrimarySmtpAddress)
               else:
                   print(2, msg.SenderEmailAddress)
    return render(request,'Home/About.html')

So any suggestion to solve this problem?

tibas
  • 139
  • 13
  • 1
    I am not familiar with how Django works, but COM needs to have the sub-system initialized. `win32com` usually does that without you knowing, BUT only in the main thread. If you script is running in another thread, then you need to initialize COM explicitly. Try `from pythoncom import CoInitialize`, then call `CoInitialize()` at the start of your function. http://timgolden.me.uk/pywin32-docs/pythoncom__CoInitialize_meth.html – DS_London Dec 09 '22 at 16:25
  • 1
    It isn't related to Django. Please see [this answer](https://stackoverflow.com/a/69396952/3219121). You have to import pythoncom and then use dispatch method this way: `win32.Dispatch('Outlook.Application', pythoncom.CoInitialize())` – matagus Dec 09 '22 at 16:26

0 Answers0