Create new outlook exchange server email in python with win32com

Question:

‘Application.CreateItemFromTemplate’ and ‘Application.CreateItem()’ don’t work. I believe it has something to do with the fact that I’m running Outlook Exchange Office 365 instead of the standard outlook session.

I am able to find emails in my mailbox and open them, but I am not able to find a way to create a new email.

my code:

import win32com.client

pythoncom.CoInitialize()
outlook = win32com.client.dynamic.Dispatch("Outlook.Application").GetNameSpace('MAPI')
inbox = outlook.GetDefaultFolder(6)
sentbox = outlook.GetDefaultFolder(5)
all_sentbox = sentbox.Items
all_inbox = inbox.Items
folders = inbox.Folders
tryopen = outlook.CreateItemFromTemplate(r'Documentsa.oft')

error:

tryopen = outlook.CreateItemFromTemplate(r'Documentsa.oft')
  File "C:UsersmePycharmProjectspythonProjectvenvlibsite-packageswin32comclientdynamic.py", line 639, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.CreateItemFromTemplate
Asked By: HalPlz

||

Answers:

Firstly, you need to specify the absolute file path when calling CreateItemFromTemplate – Outlook is an out-of-proc COM library running in the outlook.exe address space, so its current folder is different from that of your app.

Secondly, CreateItemFromTemplate is exposed by the Application object, not Namespace. You need to store win32com.client.dynamic.Dispatch("Outlook.Application") in a separate variable rather than using it as an implicit variable to call Application.GetNameSpace('MAPI').

Naming your variables to reflect their type would also be a good idea – outlook probably can better called namespace or ns, while return value of the Dispatch("Outlook.Application") call can be named application or app.

Creating a new email now works! per Dmitry Streblechenko’s answer. However, it says I don’t have permission to open the template file – which is another question.

outlook = win32com.client.dynamic.Dispatch("Outlook.Application")
outlook2 = outlook.GetNameSpace('MAPI')
tryopen = outlook.CreateItem(0x0)
Answered By: HalPlz