Share

SENDING ATTACHMENT EMAILS VIA PYTHON USING “PYWIN32”

By: Bhagesh Kumar

In one of my articles, I discussed about Python’s mail receiving capability from OutLook via “pywin32” library. If you haven’t read that article click Reading Outlook emails in Python.

In this article I will discuss about sending mails from Outlook with one or more attachments using same “pywin32” library.

Let’s get to work now.

Prerequiste:

We need to install pywin32 first, skip this section if you already have this library.

pip install pywin32

After successful installation import client from this library as described below.

import win32com.client

The first thing is to initiate the outlook application by creating its object as given below. For sending email we have to create an object because the meeting invite, email, calendar are considered as item objects in outlook.  You can create an object with the following code.

outlook = win32com.client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)

There are several attributes in mail item like CC,BCC, subject, body, HTMLbody and as well as attachments which will be set during sending email. As you can look this in below code that how I set the attributes mentioned in this section.

mail.To = 'recipientemail@domain.com'
mail.Subject = 'Test Email'
mail.HTMLBody = 'anyHTML Code'
mail.Body = 'Text mail body'
mail.Attachments.Add('file1')
mail.Attachments.Add('file2')
mail.CC = 'CC email address'
mail.BCC = 'BCC email address'

Finally you can send the email by just one line of code.

mail.sent()

Complete code will look like as.

import win32com.client



outlook = win32com.client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'recipientemail@domain.com'
mail.Subject = 'Test Email'
mail.HTMLBody = 'anyHTML Code'
mail.Body = 'Text mail body'
mail.Attachments.Add('file1')
mail.Attachments.Add('file2')
mail.CC = 'CC email address'
mail.BCC = 'BCC email address'


mail.sent()