Rehmat's Blog

Rehmat Alam
Rehmat Alam

Posted on

Asynchronous Email Sending in Python with AWS SES

The go-to AWS SDK boto3 is really great but if you are going to write async Python code, then boto3 isn't the option as it only offers the blocking sync operations. I was developing a FastAPI microservices where I decided to use Amazon SES for email sending and I found a library called aiobotocore that allows you to send emails through Amazon SES asynchronously in Python.

Here is how you can do it. Let's get started by installing the package.

pip3 install aiobotocore
Enter fullscreen mode Exit fullscreen mode

And then here is how you can send the email.

from aiobotocore.session import get_session

AWS_REGION = 'aws-region'
AWS_ACCESS_KEY_ID = 'access-key'
AWS_SECRET_ACCESS_KEY = 'secret-key'
SENDER_EMAIL = '[email protected]'


async def send_email(to_email: str, subject: str, text: str):
    session = get_session()
    try:
        async with session.create_client('ses',
                                         region_name=AWS_REGION,
                                         aws_access_key_id=AWS_ACCESS_KEY_ID,
                                         aws_secret_access_key=AWS_SECRET_ACCESS_KEY) as client:
            response = await client.send_email(
                Source=SENDER_EMAIL,
                Destination={'ToAddresses': to_email},
                Message={
                    'Subject': {'Data': subject},
                    'Body': {'Text': {'Data': text}}
                }
            )
        return {
            'status': True,
            'error': None
        }
    except Exception  as e:
        return {
            'status': False,
            'error': str(e)
        }
Enter fullscreen mode Exit fullscreen mode

I hope this helps you in sending emails through SES the async way.

Top comments (0)