Send email through Python using Outlook 2016 without opening it

noswear picture noswear · Jun 19, 2018 · Viewed 15.1k times · Source
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?

Answer

Eugene Astafiev picture Eugene Astafiev · Jun 19, 2018

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

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.