AWS Boto3 is the Python SDK for AWS. Boto3 can be used to directly interact with AWS resources from Python scripts. In this tutorial, we will look at how we can use the Boto3 library to perform various operations on AWS SES.

Table of contents

Prerequisites

  • Python3
  • Boto3: Boto3 can be installed using pip: pip install boto3
  • AWS Credentials: If you haven’t setup AWS credentials before, this resource from AWS is helpful.

How to verify an email on SES?

Before we can send an email using SES, we need to verify the email address using the verify_email_identity method.

def verify_email_identity():
    ses_client = boto3.client("ses", region_name="us-west-2")
    response = ses_client.verify_email_identity(
        EmailAddress="[email protected]"
    )
    print(response)

You should receive an email asking you to verify the email address: /assets/img/boto3-ses/email-verification.png


How to send an email using SES?

We will be using the send_email method from the Boto3 library to send an email. The key parameters for this method are:

  • Source: Email address to send the email from. This email address should be verified with SES before it can be used.
  • Destination: The destination for the email.
  • Message: The actual message we want to send. The message can include both plain-text as well as HTML.

Sending a plain-text email

def send_plain_email():
    ses_client = boto3.client("ses", region_name="us-west-2")
    CHARSET = "UTF-8"

    response = ses_client.send_email(
        Destination={
            "ToAddresses": [
                "[email protected]",
            ],
        },
        Message={
            "Body": {
                "Text": {
                    "Charset": CHARSET,
                    "Data": "Hello, world!",
                }
            },
            "Subject": {
                "Charset": CHARSET,
                "Data": "Amazing Email Tutorial",
            },
        },
        Source="[email protected]",
    )

/assets/img/boto3-ses/plain-email.png

Sending a HTML email

SES also allows us to send emails formatted as HTML. It is important to note that these emails can only be processed by email clients that support HTML.


def send_html_email():
    ses_client = boto3.client("ses", region_name="us-west-2")
    CHARSET = "UTF-8"
    HTML_EMAIL_CONTENT = """
        <html>
            <head></head>
            <h1 style='text-align:center'>This is the heading</h1>
            <p>Hello, world</p>
            </body>
        </html>
    """

    response = ses_client.send_email(
        Destination={
            "ToAddresses": [
                "[email protected]",
            ],
        },
        Message={
            "Body": {
                "Html": {
                    "Charset": CHARSET,
                    "Data": HTML_EMAIL_CONTENT,
                }
            },
            "Subject": {
                "Charset": CHARSET,
                "Data": "Amazing Email Tutorial",
            },
        },
        Source="[email protected]",
    )

/assets/img/boto3-ses/email-html.png


How to send an email with attachments using SES?

Boto3 provides another method to send emails called send_raw_email which we will use to send attachments to our email.

We will make use of the email package in Python to create emails of the MIME type. More information about this is available at [Real Python][https://realpython.com/python-send-email/#adding-attachments-using-the-email-package]


from email import encoders
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email_with_attachment():
    msg = MIMEMultipart()
    msg["Subject"] = "This is an email with an attachment!"
    msg["From"] = "[email protected]"
    msg["To"] = "[email protected]"

    # Set message body
    body = MIMEText("Hello, world!", "plain")
    msg.attach(body)

    filename = "document.pdf"  # In same directory as script

    with open(filename, "rb") as attachment:
        part = MIMEApplication(attachment.read())
        part.add_header("Content-Disposition",
                        "attachment",
                        filename=filename)
    msg.attach(part)

    # Convert message to string and send
    ses_client = boto3.client("ses", region_name="us-west-2")
    response = ses_client.send_raw_email(
        Source="[email protected]",
        Destinations=["[email protected]"],
        RawMessage={"Data": msg.as_string()}
    )
    print(response)

/assets/img/boto3-ses/email-attachment.png


How to create a custom verification email template using SES?

SES can also be used to send custom verification emails to users. This is useful if an application uses SES to send verification emails to their users.

First, we will create a custom verification email template that will be used in the email.



def create_custom_verification_email_template():
    ses_client = boto3.client('ses')
    response = ses_client.create_custom_verification_email_template(
        TemplateName= "CustomVerificationTemplate",
        FromEmailAddress= "[email protected]",
        TemplateSubject= "Please confirm your email address",
        TemplateContent= """
            <html>
            <head></head>
            <h1 style='text-align:center'>Please verify your account</h1>
            <p>Before we can let you access our product, please verify your email</p>
            </body>
            </html>
        """,
        SuccessRedirectionURL= "https://yourdomain.com/success",
        FailureRedirectionURL= "https://yourdomain.com/fail"
    )
    print(response)

Output

{'ResponseMetadata': {'RequestId': 'edd359a9-a980-4e37-b7aa-d42147804664', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'edd359a9-a980-4e37-b7aa-d42147804664', 'content-type': 'text/xml', 'content-length': '253', 'date': 'Sat, 19 Dec 2020 03:27:26 GMT'}, 'RetryAttempts': 0}}

How to send a custom verification email template using SES?

We can send a custom verification email using the template we created above.

Note: Your account must be approved for production (no longer in sandbox mode) to be able to send custom verification emails.


def send_custom_verification_email():
    ses_client = boto3.client("ses")
    response = ses_client.send_custom_verification_email(
        EmailAddress= "[email protected]",
        TemplateName= "CustomVerificationTemplate"
    )
    print(response)