'Python MAPI, windows service issue on windows server 2016
Im writing a script that downloads the attached document from every email in a subfolder of my Outlook inbox. The script works great when running from CMD or PyCharm. However it does not work when I run the script as a service.
Here is the part of the code I got trouble with:
import win32com.client
try:
outlook = win32com.client.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
mail_account = namespace.Folders.Item(2)
active_folder = mail_account.Folders['Inbox'].Folders['Subfolder']
message = active_folder.items.GetLast()
When running from CMD this part handles the newest email received in my Subfolder. But as a service my script times out on:
mail_account = namespace.Folders.Item(2)
It doesnt work when rewriting it to handle inboxes with names either, etc:
mail_account = namespace.Folders.Item("[email protected]")
It seems as services cannot handle the MAPI setup this way for some reason. Any help or pointers would be greatly appreciated.
Solution 1:[1]
Even if your service is running under the identity of the local user who uses Outlook and has a configured profile, Outlook (or any other Office app) cannot be used from a service.
Your only alternatives are Extended MAPI (C++ or Delphi), EWS (if you are using Exchange, it is an HTTP based protocol), or Redemption (I am its author - it's RDO family of objects wraps Extended MAPI and can be used from any language).
Solution 2:[2]
The Considerations for server-side Automation of Office article states the following:
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Your possible options are listed below:
- Use a low-level API on which Outlook is based on - Extended MAPI. Or just any third-party wrappers around that API such as Redemption.
- If you deal with Exchange server profiles you may consider using EWS, see Start using web services in Exchange for more information.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Community |