- Send email with Outlook and Python
- 22 Replies to “Send email with Outlook and Python”
- Add and Extract Attachments in Outlook Emails using Python
- Python Library to Add and Extract Outlook Email Attachments#
- Add Attachments to Outlook Email in Python#
- Extract Attachments from Outlook Emails in Python#
- Python Library to Work with Outlook Email Attachments — Get a Free License#
- Conclusion#
- Aspose’ Outlook Library for Python — Read More#
- See Also#
- How to Automate Outlook Emails With Python
- Fulfilling a Few Prerequisites
- Installing the win32com.client
- Check win32com.client Version
- Installing win32com Library
- Sending Emails From Python Using Outlook
Send email with Outlook and Python
A simple example to send emails via Outlook and Python win32com.
import win32com.client s = win32com.client.Dispatch("Mapi.Session") o = win32com.client.Dispatch("Outlook.Application") s.Logon("Outlook2003") Msg = o.CreateItem(0) Msg.To = "recipient@domain.com" Msg.CC = "more email addresses here" Msg.BCC = "more email addresses here" Msg.Subject = "The subject of you mail" Msg.Body = "The main body text of you mail" attachment1 = "Path to attachment no. 1" attachment2 = "Path to attachment no. 2" Msg.Attachments.Add(attachment1) Msg.Attachments.Add(attachment2) Msg.Send()
22 Replies to “Send email with Outlook and Python”
import win32com.client as win32 import psutil import os import subprocess # Drafting and sending email notification to senders. You can add other senders' email in the list def send_notification(): outlook = win32.Dispatch('Outlook.Application') mail = outlook.CreateItem(0x0) mail.To = 'abc@abc.com', # mail.Subject = 'Sent through Python' # mail.body = 'This email alert is auto generated. Please do not respond.' # mail.send def open_outlook(): try: subprocess.call(['C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE']) os.system('C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE'); except: print("Outlook didn't open successfully") for item in psutil.pids(): p = psutil.Process(item) if p.name() == "OUTLOOK.EXE": flag = 1 break else: flag = 0 if (flag == 1): send_notification() else: open_outlook() send_notification()
and the error:
Traceback (most recent call last):
File “C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py”, line 33, in
send_notification()
File “C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py”, line 12, in send_notification
mail.To = ‘abc@abc.com’,
File “C:\Users\satz\PycharmProjects\PYWork\venv\lib\site-packages\win32com\client\dynamic.py”, line 565, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, ‘Exception occurred.’, (4096, u’Microsoft Outlook’, u’The object does not support this method.’, None, 0, -2147352567), None)
Hi, What if i want to change “from” of email? Do you know something like
mail. from=”abc@..com” or mail.sender. None of them works for me.
Add and Extract Attachments in Outlook Emails using Python
If you want to send a document or any file within an email, you have to add it to the attachments. In various cases, while working with MS Outlook emails programmatically, you have to manipulate the attachments. For example, you may need to add/download files to/from the attachments. In this article, you will learn how to add attachments to Outlook emails in Python. We will also demonstrate how to extract the attachments and save them as files programmatically in Python.
Python Library to Add and Extract Outlook Email Attachments#
To add and extract attachments from Outlook emails, we will use Aspose.Email for Python. It is a powerful Python library that lets you seamlessly create, send, and process Outlook emails. In addition, it supports working with popular email clients. You can download the library or install it using the following command.
> pip install Aspose.Email-for-Python-via-NET
Add Attachments to Outlook Email in Python#
The following are the steps to add attachments to an Outlook email in Python.
- Load Outlook email or create a new one using MailMessage class.
- Create an instance of Attachment class to load the file to attach.
- Add attachment to the collection using MailMessage.attachments.append() or MailMessage.add_attachment() methods.
- Finally, save the email using MailMessage.save() method.
The following code sample shows how to add attachments to an Outlook email in Python.
Extract Attachments from Outlook Emails in Python#
Let’s have a look at how to extract the attachments from an Outlook email in Python.
- Load Outlook email using MapiMessage class.
- Loop through each attachment in the MapiMessage.attachments collection.
- Download and save each attachment using Attachment.save() method.
The following code sample shows how to extract attachments from an Outlook email in Python.
Python Library to Work with Outlook Email Attachments — Get a Free License#
You can add and extract attachments from MS Outlook emails without evaluation limitations using a free temporary license.
Conclusion#
In this article, you have learned how to add attachments to an Outlook email in Python. Furthermore, you have seen how to extract already attached files from an Outlook email. You can simply install Aspose.Email and integrate the provided code sample into your Python applications.
Aspose’ Outlook Library for Python — Read More#
You can explore more about the library using the documentation. Also, download a complete package of source code samples from GitHub. Furthermore, you can post your questions on our forum.
See Also#
How to Automate Outlook Emails With Python
Integrate Outlook with your Python applications and programmatically create, compose, and send emails.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
When one talks about Python, it’s difficult to overlook how far the functionalities spread and what you can achieve with just a few pieces of code. Today, sending and receiving emails is the most relevant thing, and Python’s email automation in Microsoft Outlook makes things handier.
Why spend endless moments compiling emails on an email client when you can let Python do it for you in a single instance? If you are intrigued, you must read on to see how you can send automated emails from Python using Microsoft Outlook.
Fulfilling a Few Prerequisites
Considering the two major platforms referenced in this guide, these are the prerequisites for enabling this simple yet helpful task. To get started, download and install the following:
- Microsoft Outlook: You must have the MS Outlook application installed and running on your system. You can use any email domain with Outlook, as it doesn’t have any restrictions regarding email configurations.
- win32com.client: This third-party library is essential to connect to your Microsoft applications. Since Microsoft Outlook is one such application, you need this library within Python to connect to the Outlook exchange server.
Microsoft Outlook is one of the oldest and most widely used email clients, which ranks in the list of most popular email providers after Gmail and Yahoo. In this guide, a Gmail address is configured within Outlook.
Installing the win32com.client
win32com.client is an integral aspect of this code, and you need a fully functional library to establish a connection between Microsoft Outlook and Python.
Check win32com.client Version
Before installing, you can check if win32com is already installed on your machine. Some IDE versions offer this package by default. You can cross-check if it is available with the following command.
python -m pip show pywin32
If you get an error ‘pip’ is not recognized as an internal or external command while running the above command, you can install pip on Windows, Mac, and Linux, to ensure your library installations are seamless.
After running the above command, if you receive a version number, you don’t need to install it again.
Subsequently, if you get the following error message, you need to install the win32com library on your system:
'pywin32' is not recognized as an internal or external command, operable program, or batch file.
Installing win32com Library
Open the prompt and type in the pip command to install the library from the terminal window.
python -m pip install pywin32
Follow the onscreen instructions to complete the process. You can use the —show command post-installation to verify whether win32com is successfully installed on your system.
python -m pip show pywin32
Sending Emails From Python Using Outlook
Since the prerequisites are taken care of, it’s time to start writing the code. To start with, you need to import the win32com.client library by using the import statement.
You can now write code to connect Python and Microsoft’s email application, Outlook.
ol = win32com.client.Dispatch('Outlook.Application')
- ol: New variable to store the connection reference.
- win32com.client: Windows library to establish a connection between Python and Outlook.
- Dispatch: Function to create the connection.
- Outlook.Application: This can be replaced with any Microsoft application name, as required.
Next, it is necessary to define the dimensions of the new email message so that Python understands where the content needs to be updated.
# size of the new email
olmailitem = 0x0
- olmailitem: New variable to store the dimensions.
- 0x0: Dimensions of the new email message in Python’s memory.
Python’s functions pop-open a new email item, as soon as you define the email body dimensions.
newmail = ol.CreateItem(olmailitem)
- newmail: New variable to store the new email reference.
- ol: Reference of the previously created connection between Python and Outlook.
- CreateItem(olmailitem): Command to create a new email draft.
Since every email is incomplete without a subject line, you can define it within the code so that Python adds it automatically before sending the email to the recipient. This will be visible to the recipient, so be careful how you define the case and the content.
newmail.Subject = 'Testing Mail'
- newmail: Variable to store the new mail item reference.
- Subject: This can vary, depending on what you wish to have as the subject for your email.
You can add the intended recipients within the To and CC keywords as follows:
newmail.To = 'xyz@gmail.com'
newmail.CC = 'xyz@gmail.com'
- To: Main recipient’s email address.
- CC: Copied email recipients.
With Python, you can send emails to multiple recipients. Add a semi-colon (;) separator between email IDs within the To/CC column.
Finally, once you define the subject and the recipients, you can add the email body to the new mail item before sending it to the recipients within the To and CC columns.
newmail.Body= 'Hello, this is a test email to showcase how to send emails from Python and Outlook.'
To add attachments to your email, you can use the following commands:
attach = 'C:\\Users\\admin\\Desktop\\Python\\Sample.xlsx'
newmail.Attachments.Add(attach)
As the email is ready to be sent, there are two options you can use. If you want a preview of your email before sending it to the recipients, you can use the Display() command as follows:
You can use the Send() command if you want to send the email without reviewing it beforehand.
Remember, you won’t see a preview of the email if you use the Send command directly. Use this command wisely if you are changing your email body content regularly. You can use the Python code in one go to import the library, establish the connection, and send the emails quickly.
import win32com.client
ol=win32com.client.Dispatch("outlook.application")
olmailitem=0x0 #size of the new email
newmail=ol.CreateItem(olmailitem)
newmail.Subject= 'Testing Mail'
newmail.To='xyz@gmail.com'
newmail.CC='xyz@gmail.com'
newmail.Body= 'Hello, this is a test email to showcase how to send emails from Python and Outlook.'
# attach='C:\\Users\\admin\\Desktop\\Python\\Sample.xlsx'
# newmail.Attachments.Add(attach)
# To display the mail before sending it
# newmail.Display()
newmail.Send()