Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email through Python using Outlook 2016 without opening it

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?

like image 949
noswear Avatar asked Jun 19 '18 10:06

noswear


1 Answers

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.

like image 97
Eugene Astafiev Avatar answered Sep 16 '22 19:09

Eugene Astafiev