Easily Subscribe and Unsubscribe from Contact Lists with AWS SES

Ram Potham
2 min readDec 27, 2022

--

By using AWS SES to manage your contact lists, you can easily control who receives your emails and ensure that you are only sending emails to people who have opted in to receive them. This helps ensure that your emails are delivered to a engaged and interested audience, so let’s jump into it!

Note this article follows from How to Bulk Email Sending, so please read that first!

We want to make a button on the frontend that triggers the email to be added to a contact list, so here’s how to make the backend.

To add an email to the contact list with a lambda, use the following code:

import json
import boto3
AWS_REGION = "us-east-1"
client = boto3.client('sesv2',region_name=AWS_REGION)

def lambda_handler(event, context):
# TODO implement
print(event)
email = event["queryStringParameters"]['email']
response = client.create_contact(
ContactListName= "ContactList",
EmailAddress=email,
UnsubscribeAll= False,
TopicPreferences= [
{
"TopicName": "Topic",
"SubscriptionStatus": "OPT_IN"
},
],
)
return {
'statusCode': 200,
'statusCode': 200,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET'
},
'body': json.dumps("hello world")
}

Make sure the lambda has IAM access to SES and then configure an API Gateway as a trigger. Then whenever an email is added through API Gateway with the email as a query parameter, the email will be added to the contact list!

AWS has to ways of allowing people to unsubscribe — adding an “Unsubscribe” link to the footer of your emails or adding a header which is the recommended way of unsubscribing.

Unsubscribe header

To do this, update the lambda that sends emails with the following code:

Change the code that sends emails to:

response = client.send_email(
FromEmailAddress=SENDER,
Content={
"Raw": {
"Data": msg.as_string()
}
},
ListManagementOptions={
'ContactListName': 'ContactList',
'TopicName': 'Topic'
}
)

Add the List-Unsubscribe header:

msg.add_header('List-Unsubscribe', '<admin@dailyquote.be>')

Then, in the body for your emails, insert the {{amazonSESUnsubscribeUrl}} placeholder to indicate where Amazon SES needs to insert the unsubscribe URL.

Now, people should be able to easily subscribe and unsubscribe to your emails!

Here is an implementation I’ve created. Also, this article is part of a 4 part series. The next article is Automating Email Sending with Google Sheets.

--

--

Ram Potham

Founder. AWS certified expert. Web3 enthusiast. Yoga Teacher. Artificial Intelligence student at Carnegie Mellon University.