How to Send Outlook Emails Using Python

Prerequisites

Before you begin, make sure you have:

  • Microsoft Outlook installed and set up on your PC
  • Python 3.x installed
  • The pywin32 library (used to control Windows applications like Outlook)

To install pywin32, run:

pip install pywin32

Step 1: Import the Required Module

You’ll need the win32com.client module from pywin32

import win32com.client as win32

Step 2: Start an Outlook Session

Create an instance of the Outlook application:

outlook = win32.Dispatch('outlook.application')

Step 3: Create a New Email Item

This sets up the email object:

mail = outlook.CreateItem(0)  # 0 = Mail item

Step 4: Set the Email Fields

Add the recipient, subject, and body:

mail.To = 'recipient@example.com'               # Main recipient
mail.CC = 'copy@example.com'                    # Optional: CC recipient
mail.BCC = 'hidden@example.com'                 # Optional: BCC recipient
mail.Subject = 'Hello from Python and Outlook'  # Email subject
mail.Body = 'This is an automated email sent using Python and Outlook.'  # Plain text body

Step 5: (Optional) Add Attachments

Attach a file if needed:

mail.Attachments.Add(r'C:\Path\To\Your\File.pdf')

Step 6: Send or Preview the Email

To send the email directly:

mail.Send()

To open the email for review before sending:

mail.Display()

Step 6: Complete Code

import win32com.client as win32

# Step 1: Start an Outlook session
outlook = win32.Dispatch('outlook.application')

# Step 2: Create a new email
mail = outlook.CreateItem(0)  # 0 = Mail item

# Step 3: Set email details
mail.To = 'recipient@example.com'               # Main recipient
mail.CC = 'copy@example.com'                    # Optional: CC recipient
mail.BCC = 'hidden@example.com'                 # Optional: BCC recipient
mail.Subject = 'Hello from Python and Outlook'  # Email subject
mail.Body = 'This is an automated email sent using Python and Outlook.'  # Plain text body

# Step 4: (Optional) Add attachment
attachment_path = r'C:\Path\To\Your\File.pdf'   # Replace with a valid path
mail.Attachments.Add(attachment_path)


# mail.Display()  # Use this if you want to preview before sending
mail.Send()       # Use this to send the email directly

Leave a Reply

Your email address will not be published. Required fields are marked *