How to send email from outlook in python
In the previous article, I have explained how to read and save attachments from the outlook by using pywin32 library. In this article, I will walk through with you how to send email from outlook with the same library.
You need to install the pywin32 library in your working environment.
pip install pywin32
and import this library in your script.
Let’s get started!
You will first need to initiate the outlook application by calling the below:
outlook = win32com.client.Dispatch('outlook.application')
In outlook, email, meeting invite, calendar, appointment etc. are all considered as Item object. Hence we can use the below to create an email object:
mail = outlook.CreateItem(0)
for this mail item, there are various attributes we can set, such as the below To, CC, BCC, Subject, Body, HTMLBody etc. as well as the Attachments:
mail.To = '[email protected]' mail.Subject = 'Sample Email' mail.HTMLBody = '<h3>This is HTML Body</h3>' mail.Body = "This is the normal body" mail.Attachments.Add('c:\\sample.xlsx') mail.Attachments.Add('c:\\sample2.xlsx') mail.CC = '[email protected]'
You can add multiple attachments by calling the Attachments.Add multiple times.
Trigger to send out email from outlook
With the above attributes set, you shall be able to send out the email since all the necessary info are provided. Below line of code will trigger to send email from outlook application.
You may also wonder what if you just want to reply to a particular email instead of writing new email? In this case, you will need to find out the email message first and then use the message.Reply() or message.ReplyAll() to reply to the original message. Do check on my this article.
This is just a sample demo of how to send emails, and there are plenty of things you can do with pywin32 library, do check my other related articles, such as this.
Last but not the least, welcome to any comments or questions.