Send email through Python using Outlook 2016 without opening it

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-18 10:58:28

问题


import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

# To attach a file to the email (optional):
attachment  = "Path to the attachment"
mail.Attachments.Add(attachment)

mail.Send()

The above code works totally fine. But the problem is that Outlook needs to be opened on the system and logged in, then only the mail is sent.

Is there any way of send a mail using outlook without actually running outlook application on the system?


回答1:


You need to use Outlook REST API without automating Outlook. Take a look at the following samples:

  • Create and send messages
  • Send a new message on the fly

Be aware, 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. Read more about that in the Considerations for server-side Automation of Office article.




回答2:


The problem is that message submission is asynchronous, and your code exits before the message is sent. In case of Exchange, try to turn off the cached mode - online store will send the message immediately. Otherwise (cached Exchange or PST store), you need to hold to the Outlook object until the message is actually submitted. You need to wait for the SyncObject.SyncEnd event to fire. SyncObject can be retrieved from the Namespace.SyncObjects collection ("All Accounts" is the first item in that collection).



来源:https://stackoverflow.com/questions/50926514/send-email-through-python-using-outlook-2016-without-opening-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!