问题
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