• TechOps

    Need clarity?
    Chat with our experts now

    • Web Hosting SupportWeb Hosting Support
    • Helpdesk Support

      Skilled and professional 24/7 helpdesk support

    • Product Support

      Boost your product support with our expertise

    • Managed ServicesManaged Services
    • Server Management

      Don't let server issues slow you down. Let us manage them for you

    • Server Monitoring

      Safeguard your server health with our comprehensive monitoring solutions

    • Staff AugmentationStaff Augmentation
    • Hire an Admin

      Transform your business operations with our expert administrative support

    • Hire a Team

      Augment your workforce with highly skilled professional from our diverse talent pool

  • CloudOps

    Confused?
    Discuss with our sales team now.

    • Author ProfileAWS
      Well Architected Review
    • Author ProfileFinOps As a Service

      FinOps As a Service

    • Migrate

      Upgrade the journey: Migrate & Modernize seamlessly

    • Modernize

      Effortless CloudOps mastery for seamless cloud management

    • Optimize

      Efficient CloudOps: Boosting performance through optimization

    • Manage

      Simplify compliance complexities with our dedicated service

  • DevOps

    How Supportsages
    is creating an
    impact?

    View Casestudies
    • Author Profile24/7 DevOps As a Service

      Round-the-clock DevOps for uninterrupted efficiency

    • Author ProfileCI/CD Pipeline

      Automated CI/CD pipeline for seamless deployments

    • Author ProfileInfrastructure As a Code

      Crafting infrastructure with ingenious code

    • Author ProfileDevSecOps

      Integrated security in continuous DevOps practices

    • Author ProfileHire DevOps Engineers

      Level up your team with DevOps visionaries

    • Author ProfileConsulting Services

      Navigate success with expert DevOps consulting

  • SecOps

    Expert SecOps Services
    for any Scale

    • Author ProfileVAPT

      Vulnerability Assessment and Penetration Testing

    • Author ProfileSource Code Review

      Ensuring source code security and safe practices to reduce risks

    • Author ProfileSecurity Consultation

      On demand services for improving server security

    • Author ProfileSystem Hardening

      Reduced vulnerability and proactive protection

    • Author ProfileManaged SOC

      Monitors and maintains system security. Quick response on incidents

    • Author ProfileCompliance as a Service

      Regulatory compliance, reduced risk

  • Insights

    Explore our latest
    insights and resources

    Blog

    Explore our latest articles and insights

    Case Studies

    Read about our client success stories

  • Contact Us

  • About
  • Certifications
  • Life at Supportsages
  • Events
  • Contact
  • Careers
  • Blog

  • Dedicated Support Team
  • Quasi-dedicated Support Team
  • Hire a DevOps Engineer
  • Hire a Billing Support Staff
  • Per-ticket Support Plan
  • Managed Services

  • Microsoft Azure Expert
  • AWS Cloud Expert
  • Hire a developer
SS

SupportSages

Bites of wisdom @ work


Copyright © 2008 - 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs

Ashley Merrin Shaji

  • 7 min read
Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs

Generating audio, please wait...

Introduction 

Monitoring email notifications sent via Amazon Simple Email Service (SES) is critical for maintaining the health and reliability of your email system. By combining AWS Lambda with CloudWatch Logs, you can efficiently track and process SES event types such as Bounce, Complaint, and Delivery. 

This guide walks you through directly setting up an AWS Lambda function integrated with CloudWatch Logs and Amazon SNS to monitor and log SES events, without the need for a CloudFormation template. 

Overview 

This solution will create the following components: 

  1. IAM Role: Provides the Lambda function the necessary privileges. 
  2. SNS Subscription: Connects an SNS topic to the Lambda function for SES event triggers. 
  3. Lambda Function: Processes SES notifications and logs filtered events to CloudWatch Logs. 
  4. CloudWatch Logs: Stores SES event logs, enabling detailed monitoring and troubleshooting. 

Step-by-Step Implementation 

Step 1: Create the IAM Role for Lambda 

Create an IAM role with the following permissions for your Lambda function: 

	{ 
  	"Version": "2012-10-17", 
  	"Statement": [ 
    	{ 
      	"Effect": "Allow", 
      	"Action": "sts:AssumeRole", 
      	"Principal": {"Service": "lambda.amazonaws.com"} 
    	}, 
    	{ 
      	"Effect": "Allow", 
      	"Action": [ 
        	"logs:CreateLogGroup", 
        	"logs:CreateLogStream", 
        	"logs:PutLogEvents", 
        	"logs:DescribeLogStreams" 
      	], 
      	"Resource": "arn:aws:logs:*:*:log-group:/aws/ses/*" 
    	} 
  	] 
	} 

Attach this role to the Lambda function. 

Step 2: Create an SNS Topic for SES Notifications 

  1. Navigate to the Amazon SNS console. 
  2. Create a new topic (e.g., SESNotificationsTopic). 
  3. Configure SES to publish Bounce, Complaint, or Delivery events to this topic. 
    1. Open the SES console and go to Email Receiving Rules. 
    2. Set the SNS topic under the Notification tab. 

Step 3: Write the Lambda Function 

Follow the below code to create a Python Lambda: 

	import boto3 
	import json 
	import os 
	import logging 
	import secrets 
	import time 
  	
	# Configure logging 
	logger = logging.getLogger() 
	logger.setLevel(logging.INFO) 
  	
	# Initialize CloudWatch Logs client 
	logs_client = boto3.client('logs') 
  	
	# Environment variables 
	log_group = os.getenv('GROUP_NAME', '/aws/ses/events') 
	event_type = os.getenv('EVENT_TYPE', 'Bounce') 
  	
  	
	def lambda_handler(event, context): 
    	logger.info("Received event: %s", json.dumps(event)) 
  	
    	for record in event['Records']: 
        	sns_message = json.loads(record['Sns']['Message']) 
        	notification_type = sns_message.get('notificationType') 
  	
        	if notification_type != event_type: 
            	logger.info("Skipping event of type: %s", notification_type) 
            	continue 
  	
        	log_stream = f"{time.strftime('%Y/%m/%d')}[$LATEST]{secrets.token_hex(8)}" 
  	
        	try: 
            	logs_client.create_log_group(logGroupName=log_group) 
        	except logs_client.exceptions.ResourceAlreadyExistsException: 
            	logger.info("Log group already exists: %s", log_group) 
  	
        	try: 
            	logs_client.create_log_stream(logGroupName=log_group, logStreamName=log_stream) 
        	except logs_client.exceptions.ResourceAlreadyExistsException: 
            	logger.info("Log stream already exists: %s", log_stream) 
  	
        	log_event = { 
            	'logGroupName': log_group, 
            	'logStreamName': log_stream, 
            	'logEvents': [ 
                	{ 
                    	'timestamp': int(time.time() * 1000), 
                    	'message': json.dumps(sns_message) 
                	} 
            	] 
        	} 
  	
        	response = logs_client.describe_log_streams( 
            	logGroupName=log_group, logStreamNamePrefix=log_stream 
        	) 
  	
       	if 'uploadSequenceToken' in response['logStreams'][0]: 
            	log_event['sequenceToken'] = response['logStreams'][0]['uploadSequenceToken'] 
  	
        	logs_client.put_log_events(**log_event) 
        	logger.info("Log published successfully.") 

Step 4: Deploy the Lambda Function 

  1. Environment Variables: 
    1. GROUP_NAME: CloudWatch Log Group name (e.g., /aws/ses/bounce_logs). 
    2. EVENT_TYPE: SES event type to monitor (Bounce, Complaint, or Delivery). 
  2. Timeout and Memory: 
    1. Set the timeout to 60 seconds and memory size to 128 MB. 
  3. Attach the IAM Role  
  4. Upload the Lambda Function Code: 
    1. Zip the Python code and upload it to Lambda. 

Step 5: Subscribe the Lambda Function to the SNS Topic 

  1. In the SNS console, select the topic you created earlier. 
  2. Add a subscription with the following details: 
    1. Protocol: AWS Lambda 
    2. Endpoint: The ARN of your Lambda function. 
  3. Grant SNS permission to invoke your Lambda function. 

aws lambda add-permission \ 
  --function-name <LambdaFunctionName> \ 
  --action lambda:InvokeFunction \ 
  --principal sns.amazonaws.com \ 
  --source-arn <SNSTopicARN> 

Testing and Monitoring 

  1. Test with SES Events: 
    1. Send test emails to trigger Bounce, Complaint, or Delivery events. 
  2. Verify CloudWatch Logs: 
    1. Navigate to the CloudWatch Logs console. 
    2. Check the Log Group for entries corresponding to the processed SES events. 

Benefits of AWS SES Monitoring 

  1. Centralized Logs: All SES events are logged in CloudWatch for easy access. 
  2. Custom Filtering: Monitor specific event types to improve email deliverability. 
  3. Scalability: Lambda automatically scales with incoming SES events. 
  4. Cost-Efficient: Pay only for the resources you use. 

Conclusion 

This article helps how to directly use AWS Lambda to monitor SES events efficiently, without relying on a CloudFormation template. By integrating Lambda with SNS and CloudWatch Logs, you can ensure reliable email delivery monitoring, enhancing both system reliability and customer satisfaction. 

 

  • AWS

Looking for AWS Experts?

We provide top-of-the-line custom AWS setup services tailored to your needs.

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs
  • AWS
  • DevOps
logo

Comparison of GCR (Google), ECR (Amazon), and ACR (Azure)

Comparison of GCR (Google), ECR (Amazon), and ACR (Azure)
  • DevOps
  • Azure
  • GCP
  • AWS
logo

Script to Gather Retention Details of S3 Buckets

Script to Gather Retention Details of S3 Buckets
  • AWS
  • DevOps
logo
Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs
Posts by Ashley Merrin Shaji