Working with Amazon SES in Python

Tuvshinsanaa Tuul

Tuvshinsanaa Tuul

0
(0)

Amazon Simple Email Service is a cost-effective, flexible, and scalable email service that enables developers to send mail from within any application. You can configure Amazon SES quickly to support several email use cases, including transactional, marketing, or mass email communications. This article covers how to verify sender(domain names, emails addresses) and, create email templates, and send emails in Python using the Boto3 library.

Prerequisites

To start interacting with Amazon SES programmatically and making API calls, you have to configure your Python environment.

In general, here’s what you need to have installed:

  • Python 3
  • Boto3
  • AWS CLI tools

Alternatively, you can use a Cloud9 IDE.

What is SES?

Amazon Simple Email Service is an email platform that provides an easy, cost-effective way for you to send and receive email using your own email addresses and domains. Built on the reliable and scalable infrastructure of Amazon Web Services (AWS), it is a cost-effective service for companies of all sizes that use email to communicate with their customers.

For example, you can send marketing emails such as special offers, transactional emails such as order confirmations, and other types of correspondence such as newsletters.

Difference between SNS, SQS and SES

Amazon SNSAmazon SQSAmazon SES
This service is designed to send a notification to subscribers of topics via multiple protocols such as HTTP, Email, SQS, SMS. It is a fully managed distributed publish-subscribe system (pub-sub). The core functionality of Amazon SNS is to push a message to multiple subscribers as soon as it received it from a publisher.This service is a distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages from SQS. Messages can’t be received by multiple receivers at the same time. It’s a receiver’s responsibility to receive a message, process it, and delete it. This service is a cloud-based email delivery service. Amazon SES can send HTML emails while SNS can’t. SES can also use email templates. The primary purpose of SES is to send high-volume e-mail efficiently and securely.

Sandbox mode

When you start using this service for the first time, your need to remove your AWS account from the Sandbox mode that applies certain restrictions while allowing all of the features.

When you are in the Sandbox mode, you can send a maximum of 200 messages per 24-hour period, and a maximum of 1 message per second. You can only send mail to verified email addresses and domains, or to the Amazon SES mailbox simulator.

To get out of Sandbox mode, you need to provide additional information about your domain and Sending Statistics. To do that, you need to go to AWS SES Web Console, then click on Edit your account details.

Editing Amazon SES account details
Amazon SES Sandbox – Editing Account details

Managing sender identity in SES using Boto3

Amazon Simple Email Service requires you to verify your identities (the domains or email addresses that you send email from) to confirm that you own them, and to prevent unauthorized use.

There are two ways to verify sender identities:

  • verifying an email domain
  • verifying an email address

Which one to use depends on your business requirements.

Domain verification in SES using Boto3

In this case, I’m going to use my domain name which is hosted on NameCheap.

import boto3

ses_client = boto3.client('ses')

response = ses_client.verify_domain_identity(
    Domain='luckytuvshee.me'
)

print(response)
Domain verification in SES using Boto3
Domain verification in SES using Boto3

Here’s what you’ll see in the AWS console:

SES managed domains
SES managed domains

AWS will provide you with the TXT Name and TXT Value for the TXT record, that you have to put to your DNS.

Domain verification details
Domain verification details

Once you’ve created the TXT record in your DNS, go back to the Verify a New Domain page in the Amazon SES web console and check if the domain has been verified.

If the correct TXT record is found, the domain status will change to verified.

Verified SES managed domain
Verified SES managed domain

Verify email in SES using Boto3

To verify email in SES, you need to use the verify_email_address() method of the SES client.

import boto3

ses_client = boto3.client('ses')

response = ses_client.verify_email_address(
    EmailAddress='luckytuvshee@protonmail.com'
)

print(response)
Verify email in SES using Boto3
Verify email in SES using Boto3

Here’s the email that was sent from AWS to verify the email. Click on the URL to the link in the email to verify your it.

Verify email in SES using Boto3 - Confirmation letter
Verify email in SES using Boto3 – Confirmation letter

As soon as you’ve verified the email address ownership, you’ll see it in a new status in the AWS console.

Verified email address
Verified email address

Now you can send emails on behalf of your verified email address.

List SES identities using Boto3

To list SES identities, you need to use the list_identities() method of the SES Boto3 client. This method returns a list that contains all identities (email addresses and domains) for your AWS account in the current AWS Region regardless of the verification status.

import boto3

ses_client = boto3.client('ses')

response = ses_client.list_identities()

print(response)
List SES identities using Boto3
List SES identities using Boto3

Delete SES identity using Boto3

To delete SES identity, you need to use the delete_identity() method of the Boto3 SES client. This method deletes the specified identity (an email address or a domain) from the list of identities whether the entity has verified or is in pending status.

import boto3

ses_client = boto3.client('ses')

response = ses_client.delete_identity(
    Identity='luckytuvshee1999@gmail.com'
)

print(response)
Delete SES identity using Boto3
Delete SES identity using Boto3

Managing SES email templates using Boto3

Amazon SES enables you to send emails that are personalized for each recipient by using templates. Templates include a subject line and the text and HTML parts of the email body. The subject and body sections can also contain unique values that are personalized for each recipient.

Create an email template in SES

To create an email template in SES, you need to use the create_template() method of the Boto3 SES client. For example, you can create a template to use whenever a user subscribes to a newsletter.

import boto3

ses_client = boto3.client('ses')

response = ses_client.create_template(
    Template={
        'TemplateName': 'subscribe-template',
        'SubjectPart': 'Welcome to Hands-on.cloud community',
        'TextPart': 'Thank you, you have subscribed to Hands-on.cloud',
        'HtmlPart': 'Thank you, you have subscribed to Hands-on.cloud'
    }
)

print(response)
Create an email template in SES using Boto3
Create an email template in SES using Boto3

You may check that a new template has been created in the Amazon SES web console:

Created SES email template
Created SES email template

Describe an email template in SES

To describe an email template in SES, you need to use the get_template() method of the Boto3 SES client.

import boto3

ses_client = boto3.client('ses')

response = ses_client.get_template(
    TemplateName='subscribe-template'
)

print(response['Template'])
Describe an email template in SES using Boto3
Describe an email template in SES using Boto3

List SES email templates

To list emails templates in SES, you need to use the list_templates() method of the Boto3 SES client.

import boto3

ses_client = boto3.client('ses')

response = ses_client.list_templates()

print(response['TemplatesMetadata'])
List SES emails templates using Boto3
List SES emails templates using Boto3

Update SES email template using Boto3

To update the SES email template, you need to use the update_template() method of the SES Boto3 client.

import boto3

ses_client = boto3.client('ses')

response = ses_client.update_template(
    Template={
        'TemplateName':'subscribe-template',
        'SubjectPart':'Hello World',
        'TextPart':'template text updated',
        'HtmlPart':'template text updated',
    }
)

print(response)
Update SES email template using Boto3
Update SES email template using Boto3

Delete SES email template

To delete the SES email template, you need to use the delete_template() method of the SES Boto3 client.

import boto3

ses_client = boto3.client('ses')

response = ses_client.delete_template(
    TemplateName='subscribe-template'
)

print(response)
Delete SES email template using Boto3
Delete SES email template using Boto3

Send email through SES using Boto3

In this section of the article, we’ll cover how to use the Boto3 library to send emails through Amazon SES.

Send a templated email

To send templated emails through SES, you need to use the send_templated_email() method of the SES Boto3 client. This method composes an email message using an email template and immediately queues it for sending.

Notes:

  • To send a templated emails, you must be sent from a verified email address or domain. If your account is still in the Sandbox mode, you can send emails only to verified addresses or domains, or to email addresses associated with the Mailbox Simulator.
  • The maximum message size is 10 MB.
  • The destination for the email is composed of To:, CC:, and BCC: fields. A destination can include up to 50 recipients across these three fields.
  • Parameter TemplateData is a list of replacement values to apply to the template. This parameter is a JSON object, typically consisting of key-value pairs in which the keys correspond to replacement tags in the email template.

I’ve added a new Gmail email address to the SES and sending an email to it.

import boto3

ses_client = boto3.client('ses')

response = ses_client.send_templated_email(
    Source='luckytuvshee@protonmail.com',
    Destination={
        'ToAddresses': ['luckytuvshee1999@gmail.com'],
        'CcAddresses': ['luckytuvshee1999@gmail.com'],
    },
    ReplyToAddresses=['luckytuvshee1999@gmail.com'],
    Template='subscribe-template',
    TemplateData='{"email_address": "luckytuvshee1999@gmail.com"}'
)

print(response)
Send templated email through SES using Boto3
Send a templated email through SES using Boto3

As soon as you’ve executed the code above, you should receive an email in your inbox. If you don’t see a new email, check for the Spam folder.

Email received from Amazon SES
Email received from Amazon SES

Send a plain-text email

To send a plain-text email from SES, you need to use the send_email() method of the SES Boto3 client. This method composes an email message and immediately queues it for sending.

For every message that you send, the total number of recipients (including each recipient in the To:, CC: and BCC: fields) is counted against the maximum number of emails you can send in a 24-hour period (your sending quota).

import boto3

ses_client = boto3.client('ses')

response = ses_client.send_email(
    Source='luckytuvshee@protonmail.com',
    Destination={
        'ToAddresses': ['luckytuvshee1999@gmail.com'],
        'CcAddresses': ['luckytuvshee1999@gmail.com'],
    },
    ReplyToAddresses=['luckytuvshee1999@gmail.com'],
    Message={
        'Subject': {
            'Data': 'Test Email',
            'Charset': 'utf-8'
        },
        'Body': {
            'Text': {
                'Data': 'hello world',
                'Charset': 'utf-8'
            },
            'Html': {
                'Data': 'hello world',
                'Charset': 'utf-8'
            }
        }
    }
)

print(response)
Send a plain-text email through SES using Boto3
Send a plain-text email through SES using Boto3

Send raw email

To send a plain-text email from SES, you need to use the send_raw_email() method of the SES Boto3 client. The method allows you to craft a more complex message formatting. This means that you can use HTML formatting and design your message using HTML code.

Using the send_raw_email() method, for example, is useful when you need to send a multipart MIME email (an email message that contains both a text and an attachment).

The raw data of the message needs to be base64-encoded. The Boto3 Python SDK for AWS handles base 64-encoding for you automatically.

import boto3

ses_client = boto3.client('ses')

html_data = """Subject: Subscription
MIME-Version: 1.0
Content-Type: text/HTML

<!DOCTYPE html>
    <html>
    <head>
        <style>
            h1   {color: #333;}
            p    {color: #555;}
        </style>
    </head>
    <body>
        <h1>Hi</h1>
        <p>you have subscribed to this newsletter.</p>
    </body>
</html>
"""

response = ses_client.send_raw_email(
    Source='luckytuvshee@protonmail.com',
    Destinations=[
        'luckytuvshee1999@gmail.com',
    ],
    RawMessage={
        'Data': html_data
    }
)

print(response['MessageId'])
Send raw email from SES using Boto3
Send raw email from SES using Boto3

Here’s an example of an HTML formatted message, I’ve sent to my email address:

An example of an HTML formatted message
An example of an HTML formatted message

Summary

Amazon Simple Email Service is a simple email service to configure and use. In this article, we’ve covered how to get started with Amazon SES, verify a sender domain and email address, manage email templates, and send emails in various formats using the Boto3 library.

How useful was this post?

Click on a star to rate it!

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Top rated Udemy Courses to improve you career

Subscribe to our updates

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Want to be an author of another post?

We’re looking for skilled technical authors for our blog!

Leave a comment

If you’d like to ask a question about the code or piece of configuration, feel free to use https://codeshare.io/ or a similar tool as Facebook comments are breaking code formatting.