Python Examples
Convert IP to Integer and Integer To IP in Python How to Get IPv4/IPv6 Address Range from CIDR in Python? Compare Two Objects For Equality in Python How to find Duplicate Elements from a List in Python Convert Timestamp to datetime in Python Convert datetime to Timestamp in Python Generate Random String of Specific Length in Python Encryption and Decryption of Strings in Python The string module in Python Convert string to bytes in Python Convert bytes to string in Python Convert string to datetime and datetime to string in Python Call a function Asynchronously from within a Loop and wait for the Results in Python Remove Duplicate Elements from a List in Python Caching in Python with Examples How to Bulk Insert and Retrieve Data from Redis in Python How to Write Unit Test in Python Read and Write CSV Files in Python Read and Write Data to a Text File in Python How to Convert CSV to JSON in Python Create ICS Calendar File in Python Install Python on Windows 10/11 Install Python on Ubuntu 20.04 or 22.04.3 Python - Install Virtual Environment How to Find a Specific Field Value from a JSON list in Python Download and Unzip a Zipped File in Python Python Install PIP Python Install Virtual Environment How to Fix Python Error: string argument without an encoding Compare Two JSON files in Python How to Hash a Dictionary Object in Python? Create a Digital Clock in Python Create Multiple URLs Using Each Path of a URL in Python Send an Email with Multiple Attachments using Amazon SES in Python SQLAlchemy Query Examples for Effective Database Management SQLAlchemy Query to Find IP Addresses from an IP Range in Bulk How to Create and Use Configuration files in a Python Project Check if a Value Already Exists in a List of Dictionary Objects in Python How to Split Large Files by size in Python? Fixing - Running Scripts is Disabled on this System Error on Windows Generating QR Codes in Python Reading QR Codes in Python

Send an Email with Multiple Attachments using Amazon SES in Python

  • Last updated Apr 04, 2024

Amazon SES is short for Amazon Simple Email Service. It is a low-cost, scalable email service that allows developers to send email from any application. Amazon SES can be quickly configured to support a variety of email use cases, such as transactional, marketing, or mass email communications. Amazon SES allows us to send email securely, globally, and at scale.

In this tutorial, we will show you how to send email with attachments using Amazon SES in Python.

Install the Boto3 SDK for Python

Boto3 SDK is a Python library for AWS. First, install the latest version of Boto3 SDK using the following command:

pip install boto3
Verifying Email Address

Before you can send email using SES, you will need to verify the sender email address so as to ensure that you do not abuse it by sending spam to others. Only verified email addresses or domains can send email through SES. By verifying an email address, you prove that you are the owner of that email address and that you want SES to send email from it.

When you verify an email address using the example code below, SES sends an email to the specified address. The email address is verified when the link is clicked in the email.

import boto3

# Create SES client
ses_client = boto3.client('ses')

response = ses_client.verify_email_identity(
  EmailAddress = 'sender@example.com'
)
print(response)
Sending Simple Email without Attachment

To send a simple email without attachment, you can use the send_email function provided by the boto3 SES client library. For example:

import boto3

ses_client = boto3.client('ses')

response = ses_client.send_email(
    Source='sender@domain.com',
    Destination={
        'ToAddresses': ['receiver@domain.com', 'receiver2@domain.com'],
        'CcAddresses': ['ccreceiver@domain.com'],
        'BccAddresses': ['bccreceiver@domain']
    },
    Message={
        'Subject': {
            'Data': 'Hello Buddy',
            'Charset': 'UTF-8'
        },
        'Body': {
            'Text': {
                'Data': 'This is simple text email.',
                'Charset': 'UTF-8'
            },
            'Html': {
                'Data': '<html><head><title>Hello Buddy</title></head><body><h1>Hello Buddy</h1><p>This is html based email.</p></body></html>',
                'Charset': 'UTF-8'
            }
        }
    },
)
Sending Raw Email with Attachments

To send an email with multiple attachments using Amazon SES, we can use the send_raw_email function provided by the boto3 SES client library:

import os
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

ses_client = boto3.client('ses')

SENDER = "sender@domain.com"
RECEIVER = "receiver@domain.com"
CHARSET = "utf-8"
msg = MIMEMultipart('mixed')
msg['Subject'] = "Register Today"
msg['From'] = SENDER
msg['To'] = RECEIVER

msg_body = MIMEMultipart('alternative')
# text based email body
BODY_TEXT = "Dear,\n\rPlease using the given link to register today."
# HTML based email body
BODY_HTML = "<html><head><title>Hello Buddy</title></head><body><h1>Hello Buddy</h1><p>This is html based email.</p></body></html>"
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)

msg_body.attach(textpart)
msg_body.attach(htmlpart)

# Full path to the file that will be attached to the email.
ATTACHMENT1 = "path/to/registration_form.pdf"
ATTACHMENT2 = "path/to/prospectus_form.pdf"

# Adding attachments
att1 = MIMEApplication(open(ATTACHMENT1, 'rb').read())
att1.add_header('Content-Disposition', 'attachment',
                  filename=os.path.basename(ATTACHMENT1))
att2 = MIMEApplication(open(ATTACHMENT1, 'rb').read())
att2.add_header('Content-Disposition', 'attachment',
                  filename=os.path.basename(ATTACHMENT2))

msg.attach(msg_body)
msg.attach(att1)
msg.attach(att2)

try:
    response = ses_client.send_raw_email(
        Source=SENDER,
        Destinations=[
            RECEIVER
        ],
        RawMessage={
            'Data': msg.as_string(),
        },
        ConfigurationSetName="ConfigSet"
    )
    print("Message id : ", response['MessageId'])
    print("Message send successfully!")
except Exception as e:
    print("Error: ", e)