
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.
Prerequisite:
You need to install the pywin32 library in your working environment.
pip install pywin32
and import this library in your script.
import win32com.client
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 = 'contact@company.com' 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 = 'somebody@company.com'
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.
mail.Send()
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.
Conclusion:
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. Follow me on twitter for more updates.
messages = messages.Restrict(“[ReceivedTime] >= ‘” + received_dt + “‘”)
^
SyntaxError: invalid character in identifier
I keep getting this error when I try to run the code what can I do to fx this
how to send to multiple recipients
You can simply put all the recipient emails into a “;” separated string and pass it to mail.To. e.g.:
mail.To = “abc@company.com;def@company.com”
Help.
I can’t even start the program.
install is a syntax error
Which exact line has thrown out the syntax error for you?
Literally the first one lol
Do you mean the syntax error for “pip install pywin32” ? You will need to execute it in your command line window if you are using Windows OS, not in the Python interactive mode.
Was very helpful! Thanks. How does it determine who is sending the email? Can I change that?
Hi Ruth,
Thanks for reading. It uses the 1st account you configured in outlook as the default sender. If you want to specify another sender, you will need to use something like:
mail._oleobj_.Invoke(*(64209, 0, 8, 0, outlook.Session.Accounts[2]))
mail.To = ‘someone@company.com’
mail.Subject = ‘Sample Email’
mail.Send()
Assuming you want to send email from your 2nd account configured in your outlook.
See the complete example from change sender account pywin32.
Hi Ken,
I am in the same situation where I want to send the email from a different account. Is there any way to send it from the web email of a different account?
Hi, the pywin32 library only works when you configured your mail account in outlook application. To send from web mail, you may check if this post is workable for you.
Hi, I run the script, but nothing happened, it wont bring up oulook client at all
Hi Tom,
The script would not launch your outlook client, but in order to make it work, you shall first configure your outlook client and be able to send out email from the client itself.
Once the script run successfully, you shall see the messages from your sent folder.
Can u just tell me what we need to put in the place of html body
Hi Ramyasree, the html body allows you to do all sorts of formatting,e.g applying css, using html tables, while you cannot do them in the normal message body.
Tqq can u just say me how to send zip file in attachments for excel I have used .CSV and for zip file what need to use ?
Hi Ramyasree,
The mail.Attachments.Add(‘c:\\xxx.zip’) shall work as well. have you tried that?
what should I write into mail.CC section and We don’t write our email address and password how the program know our email and password ?
Hi Hinami,
The mail.CC is optional, so you can comment out that line if you don’t need to cc anybody. The pywin32 package is calling the windows API under the hood, so you will need to have outlook client installed and configure your email account in outlook in order to read/send email.
https://www.microsoft.com/en-us/download/details.aspx?id=56972
Is the link right for outlook client ?
After I download,should everything same like example above ? (client.Dispatch part)
Yes Hinami. The pywin32 works when you have outlook configured. You may also check exchangelib if you are not working with outlook.
Very helpful! And also works on my side.
1 question, how to send email to multiple receivers?
Thanks for reading. You shall be able to put multiple recipients with semicolon e.g.: mail.To = “abc@xyz.com;bcd@xyz.com”.
cool
Hey great article but can you tell me what’s not working in my code? I want to send some files but it’s not letting me
import win32com.client
import glob
import os
os.chdir('C:\\Users\\SEBAA\\desktop')
data = [file for file in glob.glob("*.txt")]
outlook = win32com.client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'bobmarley2021@outlook.fr'
mail.Subject = 'Testing my script'
mail.Attachments.Add(data)
mail.CC = 'fox@outlook.fr'
mail.Send()
print("sent")
Hi, the mail.Attachments.Add can only add 1 file at a time, so you can iterate through your data variable to add one by one. Also make sure your file path is absolute path.
Is there any other solution because it’s not working
I’m trying to send some data to my email address what can i do?
I am actually not sure what exactly doesn’t work for you. Are you able to send out email without attachment? I suggest you hard code the attachment file path first to see if you are able to send out the email with a single attachment.
Great write up. Do you know if there is a way instead of attaching I can insert item as text (similar to here https://www.solveyourtech.com/how-to-insert-as-text-in-microsoft-outlook-for-office-365/) ? I have writeups that I would like to be included in the body when sending meeting mintues as opposed to inserting as attachments. I am not sure how to check for this capability in the pywin32 library or other Microsoft docs. Thanks for your help.
Hi Aravind,
The pywin32 library calls the Windows outlook API under the hood, so you can check the Microsoft VBA doc here to see what are the methods & properties it has for the MailItem object.
Not sure what exactly the information you want to insert it, but based on what you said, I guess you will have to either:
– read the content as string and pass it to MailItem.Body (the plain text will not have any styling)
– read the content as format it as HTML string and pass to MailItem.HTMLBody (you can style your data in the HTML)
Hey Ken,
Have you found any solution for selecting label with this library?
Labels such as – Not Classified, Public, Proprietary etc
My system used to send automatically but a few months back my organisation brought an update where we also wanted to select this label.
Now a pop up opens which asks for this label to be selected when automated run is complete.
Let me know if you have a solution.
Hi Abhijay,
Sorry for the late reply.
Is this Categories attribute that you are looking for? I don’t see any other attributes in MailItem closer to the label you described. You may try and see what it returns for this Categories attribute.
I have two different email accounts setup in my outlook. How would I select one of them to send an email from?
Hey Guiherme, hope you have found your solution. If not, you may take a look at this.
Hi, Ken!
First of all, thanks for the amazing work. This script, combined with some loops, saved me tons of work! Much appreciated!
One detail I would like your help, though: how to add the e-mail signature to it?
Thanks!
Hi Silva,
I did not try adding signature personally, but seems it’s doable if you set a default signature in outlook, and load it before you add your message body. so the idea is:
1) create new mail item – mail = outlook.CreateItem(0)
2) use mail.Display to load signature
3) merge your HTML message body into the mail.HTMLBody (NOT replace)
You can refer to this link.
Hello, what if I already have a sign to use, how can I choose it from outlook to use it on the e-mail?
How would I set up the attachment when my file name changes daily?
How to access outlook contact folder, if i have to send email ??
can anyone guide on this.
what if I want to send an email that is currently saved as a draft?