How to send emails using Python and AWS SES SMTP

Sending emails using Python and AWS’ SES service is really easy. They provide an SMTP server that you can authenticate against and send email programmatically from your python scripts.

There is a wonderfully simple Python package called emails I like to use for this purpose.

If you’re not running a Python Virtual Environment, then start by getting started here.

Otherwise, continue reading!

Getting AWS SES SMTP Setup

In order to start sending emails using AWS SES, and the SMTP server in particular, you will need to:

Using the Emails Module

pip install emails will make available a simple module that allows you to connect to an SMTP server for email sending.

Now you can write a python script as follows:

import emails

# Compose the email you want to send...
message = emails.html(
    html = "<h1>This is an email</h1><strong>We love sending emails</strong>",
    subject = "Hey, look in here!",
    mail_from = "[email protected]",
)

# Now you can send the email!
r = message.send(
    to = "[email protected]", 
    smtp = {
        "host": "your-aws-smtp-server", 
        "port": 587, 
        "timeout": 5,
        "user": "your-aws-smtp-user",
        "password": "your-aws-smtp-pass",
        "tls": True,
    },
)

# See if the email was successfully sent
print( r.status_code == 250 )

Learn more about Sending Emails using Python

The emails module used above can be found on the Python Package Index at: https://pypi.org/project/emails/

This code is backed by the following open-source contributions on Github at: https://github.com/lavr/python-emails

Tags:

Leave a Reply

Your email address will not be published.