CodeBriefly
Tech Magazine

How to handle Bounce and Complaint Notifications in AWS SES with SNS, SQS, and Lambda

0 399

Get real time updates directly on you device, subscribe now.

In this article, we will discuss “how to handle complaints and bounce in AWS SES using SNS, SQS, and Lambda”. Amazon Simple Email Service (SES) is a powerful tool for sending emails, but handling bounce and complaint notifications is crucial to maintaining a good sender reputation. AWS SES provides mechanisms to capture these notifications via Amazon Simple Notification Service (SNS), Amazon Simple Queue Service (SQS), and AWS Lambda.

This article will guide you through setting up this pipeline and provide Python code to process bounce and complaint notifications and add affected recipients to the AWS SES suppression list.

Architecture Overview

  1. SES Sends Emails: AWS SES is used to send emails.
  2. SES Triggers SNS: SES forwards bounce and complaint notifications to an SNS topic.
  3. SNS Delivers to SQS: SNS publishes these messages to an SQS queue.
  4. Lambda Processes Messages: A Lambda function reads messages from SQS, identifies bounced and complained addresses, and adds them to the SES suppression list.

Step 1: Configure AWS SES to Send Notifications

  • Go to the AWS SES console.
  • Navigate to Email Identities and select the verified email/domain.
  • Under the Feedback Forwarding section, set up SNS notifications for Bounces and Complaints.
  • Create an SNS topic and subscribe an SQS queue to it.

Step 2: Subscribe SQS Queue to SNS Topic

  • Create an SQS queue.
  • In the SNS topic settings, subscribe the SQS queue.
  • Modify the SQS queue’s access policy to allow SNS to send messages.

Step 3: Create a Lambda Function to Process Notifications

The Lambda function reads bounce and complaint notifications from SQS and adds affected email addresses to the AWS SES suppression list.

Python Code for AWS Lambda

import json
import boto3

sqs = boto3.client('sqs')
sesv2 = boto3.client('sesv2')

# Replace with your SQS queue URL
SQS_QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/YOUR_ACCOUNT_ID/YOUR_QUEUE_NAME"

def lambda_handler(event, context):
    messages = receive_sqs_messages()
    for message in messages:
        process_message(message)
        delete_sqs_message(message['ReceiptHandle'])
    return {'statusCode': 200, 'body': 'Processed messages successfully'}

def receive_sqs_messages():
    response = sqs.receive_message(
        QueueUrl=SQS_QUEUE_URL,
        MaxNumberOfMessages=10,
        WaitTimeSeconds=5
    )
    return response.get("Messages", [])

def process_message(message):
    body = json.loads(message['Body'])
    notification = json.loads(body['Message'])
    
    if 'bounce' in notification:
        bounced_addresses = [rec['emailAddress'] for rec in notification['bounce']['bouncedRecipients']]
        add_to_suppression_list(bounced_addresses)
    
    if 'complaint' in notification:
        complained_addresses = [rec['emailAddress'] for rec in notification['complaint']['complainedRecipients']]
        add_to_suppression_list(complained_addresses)

def add_to_suppression_list(email_addresses):
    for email in email_addresses:
        sesv2.put_suppressed_destination(
            EmailAddress=email,
            Reason='BOUNCE'  # Use 'COMPLAINT' for complaint types
        )
        print(f"Added {email} to SES suppression list")

def delete_sqs_message(receipt_handle):
    sqs.delete_message(
        QueueUrl=SQS_QUEUE_URL,
        ReceiptHandle=receipt_handle
    )

Step 4: Deploy the Lambda Function

  • Go to the AWS Lambda console.
  • Create a new Lambda function.
  • Attach the necessary IAM permissions:
    • Read from SQS
    • Write to SES suppression list
  • Deploy the function and configure it to trigger from the SQS queue.

Step 5: Test the Pipeline

  • Send a test email using SES to an invalid address.
  • Check the SQS queue for incoming messages.
  • Verify that the email address is added to the SES suppression list.

Conclusion

In this article, we are discussing “How to handle Bounce and Complaint Notifications in AWS SES with SNS, SQS, and Lambda”. This setup ensures that bounce and complaint notifications are handled efficiently, preventing future emails to problematic addresses and maintaining a good sender reputation. By leveraging AWS Lambda, SQS, and SNS, you can automate the process and improve email deliverability.

Keep learning and stay safe 🙂


You may like:

How to Setup AWS Pinpoint (Part 1)

How to Setup AWS Pinpoint SMS Two Way Communication (Part 2)?

Basic Understanding on AWS Lambda

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More