We should learn Amazon SES to build scalable, reliable, and cost-efficient email systems directly within their cloud infrastructure.
It enables automation for alerts, notifications, and transactional emails while ensuring high deliverability and seamless integration with CI/CD pipelines and application workflows.
⚡ Quick Reference
Keep the momentum going — everything you need on LearnXOps in one place:
- 🎓 Courses — Video courses & AI-built courses
- 📚 Ebooks — Community ebooks & your own
- 🧪 All Labs & Challenges — DevOps, Cloud, SRE & more
- ☸️ Kubernetes Labs & Playground — kind clusters, playground & challenges
- 🤖 AI Agent & Bot Labs — OpenClaw · Hermes · CrewAI · LangGraph · MCP
📚 Key Learnings
- Understand what Amazon Simple Email Service (SES) is and why it’s used for transactional and bulk email delivery.
- Explore key components — SMTP interface, API integration, email identities, and configuration sets.
- Learn how to verify domains and email addresses for sending.
- Understand email deliverability, DKIM, SPF, and feedback loops.
- Explore monitoring metrics (bounces, complaints, open/click tracking).
🧠 Learn here
📧 Amazon Simple Email Service (SES)
What is Amazon SES?
Amazon Simple Email Service (SES) is a cloud-based email sending service offered by AWS that enables developers and businesses to send transactional, marketing, and bulk emails at scale. It provides a reliable, cost-effective, and secure way to send email messages without managing on-premises email servers or third-party SMTP services.
SES is built on the reliable AWS infrastructure, offering features like reputation management, feedback loops, deliverability analytics, and flexible integration options (SMTP interface, AWS SDKs, and APIs).
Why Use Amazon SES?
| Use Case | Description |
|---|---|
| Transactional Emails | Send automated notifications, password resets, order confirmations, and OTPs reliably and at scale. |
| Marketing & Bulk Emails | Distribute newsletters, promotional campaigns, or product updates to large audiences efficiently. |
| Cost-Effective Delivery | Pay only for what you send — no upfront commitments or infrastructure management required. |
| Scalability & Reliability | Leverage AWS’s global infrastructure to ensure fast, reliable, and high-volume email delivery. |
| Deliverability Insights | Track email bounces, complaints, and open/click metrics to improve campaign performance. |
| Security & Compliance | Supports domain authentication (SPF, DKIM, DMARC) and integrates with AWS IAM for fine-grained access control. |
Key Features:
- SMTP and API-based email sending
- Dedicated IP and IP pool management
- Email receiving capabilities
- Reputation metrics and dashboards
- Feedback notifications (bounces, complaints)
- Support for custom domains and DKIM signing
Integration Options
- SMTP Interface: Easily integrate SES with any mail client or application that supports SMTP.
- AWS SDK / API: Programmatically send and track emails via AWS SDKs for Python (Boto3), Node.js, Go, and others.
- AWS Services Integration: Combine with Lambda, SNS, and S3 for automated email workflows and event-driven systems.
Common Scenarios
- Sending OTPs or verification emails from web/mobile apps
- Delivering system alerts or notifications to admins
- Automating email reports and logs
- Running large-scale email marketing campaigns
Key Components

✅ Assumptions: You have an AWS account, selected a Region that supports SES, and your account/region is either out of the sandbox or you’re sending to verified recipients while still in sandbox.
Prerequisites & Setup Checklist
- Region: Decide a Region (e.g.,
us-east-1). Use it consistently. - SES Sandbox: If in sandbox, you can only send to verified identities. Request production access to send to anyone.
- Verify identities: Verify your domain and/or from email. Enable DKIM for best deliverability.
- Authentication:
- For SMTP: Create SES SMTP credentials (not the same as IAM keys).
- For API: Use IAM credentials/role with
ses:SendEmail/ses:SendRawEmail(or v2 permissions).
- DNS: Add SPF (via your domain’s TXT), DKIM (CNAMEs), and consider DMARC.
1) SMTP Interface
The SMTP interface lets any SMTP‑capable client send emails via SES. Great for quick integrations or existing tooling.
SMTP Endpoint
email-smtp.<region>.amazonaws.com (e.g., email-smtp.us-east-1.amazonaws.com)
Ports: 25, 587 or 2587 (STARTTLS); 465 or 2465 (TLS wrapper)
Port 25 is often blocked (for example on EC2), so prefer 587
Python (SMTP + STARTTLS)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
SMTP_HOST = "email-smtp.us-east-1.amazonaws.com"
SMTP_PORT = 587 # STARTTLS
SMTP_USERNAME = "YOUR_SES_SMTP_USERNAME"
SMTP_PASSWORD = "YOUR_SES_SMTP_PASSWORD"
FROM = "Sender Name <[email protected]>"
TO = ["[email protected]"]
SUBJECT = "Hello from SES SMTP"
msg = MIMEMultipart("alternative")
msg["Subject"] = SUBJECT
msg["From"] = FROM
msg["To"] = ", ".join(TO)
# Optional: use a Configuration Set via header
msg["X-SES-CONFIGURATION-SET"] = "my-config-set"
text = "Plaintext fallback"
html = """
<html>
<body>
<h1>Hi from SES via SMTP</h1>
<p>This is a test message.</p>
</body>
</html>
"""
msg.attach(MIMEText(text, "plain"))
msg.attach(MIMEText(html, "html"))
with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
server.ehlo()
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.sendmail(FROM, TO, msg.as_string())
print("Email sent via SES SMTP!")
Node.js (Nodemailer)
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
secure: false, // STARTTLS
auth: {
user: process.env.SES_SMTP_USERNAME,
pass: process.env.SES_SMTP_PASSWORD,
},
});
async function send() {
const info = await transporter.sendMail({
from: 'Sender Name <[email protected]>',
to: '[email protected]',
subject: 'Hello from SES SMTP',
text: 'Plaintext fallback',
html: '<h1>Hi from SES via SMTP</h1><p>This is a test message.</p>',
headers: {
'X-SES-CONFIGURATION-SET': 'my-config-set', // optional
},
});
console.log('Message sent:', info.messageId);
}
send().catch(console.error);
Pro tips
- Prefer
587with STARTTLS for broader firewall compatibility. - Use raw MIME to include attachments, inline images, and custom headers.
2) API Integration (SES v2)
The SES v2 API provides modern endpoints, event configuration, and rich features. Use AWS SDKs for robust programmatic control.
Python (Boto3 – SES v2)
import boto3
region = "us-east-1"
ses = boto3.client("sesv2", region_name=region)
response = ses.send_email(
FromEmailAddress="[email protected]",
Destination={
"ToAddresses": ["[email protected]"],
# "CcAddresses": [],
# "BccAddresses": [],
},
Content={
"Simple": {
"Subject": {"Data": "Hello from SES API"},
"Body": {
"Text": {"Data": "Plaintext fallback"},
"Html": {"Data": "<h1>Hi via SES API</h1><p>This is a test.</p>"},
},
}
},
ConfigurationSetName="my-config-set", # optional
EmailTags=[{"Name": "app", "Value": "billing-service"}],
)
print("MessageId:", response["MessageId"])
Attachments? Use Raw content and pass the MIME message bytes; the SDK handles the base64 encoding.
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg['Subject'] = 'Invoice Attached'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.attach(MIMEText('See attached invoice.', 'plain'))
with open('invoice.pdf', 'rb') as f:
part = MIMEApplication(f.read())
part.add_header('Content-Disposition', 'attachment', filename='invoice.pdf')
msg.attach(part)
raw_bytes = msg.as_bytes()
# Pass the MIME bytes as-is: the SDK base64-encodes them for you
ses = boto3.client('sesv2', region_name='us-east-1')
ses.send_email(
FromEmailAddress='[email protected]',
Destination={'ToAddresses': ['[email protected]']},
Content={'Raw': {'Data': raw_bytes}},
ConfigurationSetName='my-config-set'
)
Node.js (AWS SDK v3 – SES v2)
import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2';
const client = new SESv2Client({ region: 'us-east-1' });
async function send() {
const cmd = new SendEmailCommand({
FromEmailAddress: '[email protected]',
Destination: { ToAddresses: ['[email protected]'] },
Content: {
Simple: {
Subject: { Data: 'Hello from SES API' },
Body: {
Text: { Data: 'Plaintext fallback' },
Html: { Data: '<h1>Hi via SES API</h1><p>This is a test.</p>' },
},
},
},
ConfigurationSetName: 'my-config-set', // optional
EmailTags: [{ Name: 'app', Value: 'billing-service' }],
});
const res = await client.send(cmd);
console.log('MessageId:', res.MessageId);
}
send().catch(console.error);
Pro tips
- Use
EmailTagsto tag emails for analytics & filtering. - Use
Rawfor attachments and advanced headers. - Retries: the SDKs include retry logic; tune backoff for throughput.
3) Email Identities (Domains & Addresses)
SES only allows sending from verified identities (domain or email). Verifying a domain lets you send from any address at that domain (e.g., *@example.com).
Steps
- Create identity (domain):
- Console: SES → Identities → Verify a new domain → Enable Easy DKIM.
- Add DNS records: SES will provide DKIM CNAMEs (and optionally a custom MAIL FROM domain). Apply them in Route 53 or your DNS provider.
- SPF: Ensure your domain’s TXT includes or is compatible with
v=spf1 include:amazonses.com ~all(or your consolidated SPF policy). - DMARC (recommended): Add a
_dmarc.example.comTXT, e.g.,v=DMARC1; p=none; rua=mailto:[email protected]. - Verify individual sender (optional): For single email use cases, you can verify just
[email protected]instead of the whole domain.
CLI example:
# Easy DKIM is on by default for a domain identity; the output
# lists the three DKIM tokens to publish as CNAME records
aws sesv2 create-email-identity --email-identity example.com
Gotchas
- DNS may take time to propagate; DKIM must show Verified for optimal deliverability.
- Sandbox: you must verify both sender and recipient while in sandbox (unless moved to production).
4) Configuration Sets
A Configuration Set is a named collection of rules for how SES handles your mail—think: event destinations, dedicated IP pools, and default tags.
Why use them?
- Metrics & Events: Forward bounces/complaints/deliveries/opens/clicks to SNS, Amazon Data Firehose, or CloudWatch.
- IP Pools: Assign to dedicated IPs and manage warm‑up.
- Default Tags: Apply tags consistently.
Create a configuration set (CLI)
aws sesv2 create-configuration-set --configuration-set-name my-config-set
Add an event destination (e.g., SNS for bounces/complaints)
aws sesv2 create-configuration-set-event-destination \
--configuration-set-name my-config-set \
--event-destination-name sns-events \
--event-destination '{
"Enabled": true,
"MatchingEventTypes": ["SEND","DELIVERY","BOUNCE","COMPLAINT","REJECT","OPEN","CLICK"],
"SnsDestination": {"TopicArn": "arn:aws:sns:us-east-1:123456789012:ses-events"}
}'
Use a configuration set when sending
- SMTP: add header
X-SES-CONFIGURATION-SET: my-config-set(shown in the SMTP examples above) - API: set
ConfigurationSetName: 'my-config-set'(shown in the SDK examples)
Minimal IAM policy for API sending (v2)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ses:SendEmail",
"ses:SendRawEmail"
],
"Resource": "*"
}
]
}
Scope to specific identities withConditionkeys likeses:FromAddressor to specific resources if you manage identities as ARNs.
Troubleshooting
- 554 Message rejected → From identity not verified, sandbox restrictions, or policy issues
- TLS/SSL errors (SMTP) → Ensure correct port & STARTTLS vs SSL
- Low deliverability → Warm up IPs, enable DKIM, maintain list hygiene, monitor bounces/complaints
- Missing events → Confirm configuration set name, event destination status, and IAM permissions for SNS/Kinesis
Amazon SES Monitoring & Deliverability Metrics
Now, let me explain how to measure, alert, and analyze key SES metrics: bounces, complaints, and engagement (opens/clicks). It includes setup steps, CloudWatch metrics/alarms, SNS/Kinesis pipelines, and sample processors (Python & Node.js).
✅ Assumptions: You’re using SES v2, have a Configuration Set, and your sending identities (domain or from address) are verified with DKIM enabled.
1) What to Track (and Why)
| Metric | What it means | Why it matters | Target/Threshold |
|---|---|---|---|
| Bounce Rate | % of emails rejected by recipient servers | High bounces harm reputation & can throttle/block | < 2% (aim lower) |
| Complaint Rate | % of recipients marking mail as spam | Complaints are highly negative signals | < 0.1% |
| Delivery Rate | % successfully accepted by recipient servers | Baseline health of mail stream | > 98% |
| Open Rate | % of delivered emails opened | Engagement indicator (requires tracking pixel) | Varies by use case |
| Click Rate | % of delivered emails with link clicks | Measures CTA effectiveness | Varies by use case |
| Rejects | Rejected by SES due to policy/limits | Indicates configuration/throughput issues | ~0% |
| Rendering Failures | Template personalisation issues | Prevent broken content | ~0% |
Note: SES computes Account-level and ConfigurationSet-level metrics. Prefer Config Set for granular control per app/tenant.
2) Enable Event Collection & Engagement Tracking
A) Configuration Set – Events → SNS/Firehose/CloudWatch
- Create/update a Configuration Set and add Event Destinations for:
SEND, DELIVERY, BOUNCE, COMPLAINT, REJECT, OPEN, CLICK, RENDERING_FAILURE. - Destinations:
- SNS → real-time notifications → triggers Lambda/webhooks.
- Amazon Data Firehose → S3 → durable lake for analytics (Athena/Glue/QuickSight).
- CloudWatch → built-in dashboards/metrics & alarms.
B) Enable Open/Click Tracking
- Open and click tracking works once the configuration set publishes OPEN and CLICK events. A custom redirect domain (tracking options, a CNAME you own) is optional but helps deliverability and branding.
- Use the same config set in your send calls (SMTP header
X-SES-CONFIGURATION-SETor APIConfigurationSetName).
3) CloudWatch Metrics & Example Alarms
SES metrics namespace:
AWS/SES— account-wide metrics, includingReputation.BounceRateandReputation.ComplaintRate, plus per-configuration-set metrics once you add a CloudWatch event destination with a dimension such asses:configuration-set. There is no separate configuration-set namespace.
Typical metric names: Send, Delivery, Bounce, Complaint, Reject, Open, Click, RenderingFailure.
Example: Alarm on Complaint Rate (> 0.1%)
aws cloudwatch put-metric-alarm \
--alarm-name ses-complaint-rate-high \
--namespace "AWS/SES" \
--metric-name Reputation.ComplaintRate \
--statistic Average \
--period 3600 \
--evaluation-periods 1 \
--threshold 0.001 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:123456789012:alerts
Reputation.ComplaintRate is account-wide and a fraction (0.001 = 0.1%). For a single configuration set, turn on its reputation metrics: aws sesv2 put-configuration-set-reputation-options --configuration-set-name my-config-set --reputation-metrics-enabledExample: Alarm on Bounce Count (> N in 5 min)
# Needs a CloudWatch event destination on the configuration set
# with a dimension named ses:configuration-set (value source: message tag)
aws cloudwatch put-metric-alarm \
--alarm-name ses-bounce-count-high \
--namespace "AWS/SES" \
--metric-name Bounce \
--dimensions Name=ses:configuration-set,Value=my-config-set \
--statistic Sum \
--period 300 \
--evaluation-periods 1 \
--threshold 25 \
--comparison-operator GreaterThanOrEqualToThreshold \
--alarm-actions arn:aws:sns:us-east-1:123456789012:alerts
For rates, create metric math: BounceRate = Bounce / (Delivery + Bounce + Complaint + Reject) and alarm on the expression.4) SNS Notification Shapes & Processors
SES sends structured JSON (via SNS) for events. Build a consumer to update suppression lists, CRM flags, and analytics.
A) Lambda (Python) – Handle Bounce/Complaint
import json
import boto3
from urllib.parse import urlparse
ddb = boto3.resource('dynamodb')
supp_table = ddb.Table('email_suppression')
BOUNCE_TYPES_BLOCK = {"Permanent"}
def handler(event, context):
for record in event['Records']:
msg = json.loads(record['Sns']['Message'])
# Configuration-set event publishing uses eventType;
# identity feedback notifications use notificationType
notification_type = msg.get('eventType') or msg.get('notificationType')
if notification_type == 'Bounce':
bounce = msg['bounce']
if bounce.get('bounceType') in BOUNCE_TYPES_BLOCK:
for rcpt in bounce.get('bouncedRecipients', []):
email = rcpt['emailAddress'].lower()
supp_table.put_item(Item={
'email': email,
'reason': 'bounce',
'detail': bounce.get('bounceSubType', 'Unknown')
})
elif notification_type == 'Complaint':
comp = msg['complaint']
for rcpt in comp.get('complainedRecipients', []):
email = rcpt['emailAddress'].lower()
supp_table.put_item(Item={
'email': email,
'reason': 'complaint'
})
return { 'statusCode': 200 }
B) Lambda (Node.js) – Normalize Event → Firehose/S3
export const handler = async (event) => {
const records = event.Records || [];
const normalized = [];
for (const r of records) {
const msg = JSON.parse(r.Sns.Message);
const type = msg.eventType || msg.notificationType; // Bounce | Complaint | Delivery | Open | Click
const base = {
type,
mailMessageId: msg.mail?.messageId,
timestamp: msg.mail?.timestamp,
source: msg.mail?.source,
sesSourceIp: msg.mail?.sourceIp,
tags: msg.mail?.tags || {},
};
if (type === 'Bounce') {
for (const rcpt of msg.bounce?.bouncedRecipients || []) {
normalized.push({ ...base, email: rcpt.emailAddress, detail: msg.bounce });
}
} else if (type === 'Complaint') {
for (const rcpt of msg.complaint?.complainedRecipients || []) {
normalized.push({ ...base, email: rcpt.emailAddress, detail: msg.complaint });
}
} else if (type === 'Delivery') {
for (const rcpt of msg.delivery?.recipients || []) {
normalized.push({ ...base, email: rcpt, detail: msg.delivery });
}
} else if (type === 'Open' || type === 'Click') {
normalized.push({ ...base, detail: msg[type.toLowerCase()] || {} });
}
}
// TODO: Put to Firehose (or S3) for analytics
// const client = new FirehoseClient({ region: process.env.AWS_REGION });
// await client.send(new PutRecordBatchCommand({ DeliveryStreamName: process.env.STREAM, Records: normalized.map(x => ({ Data: Buffer.from(JSON.stringify(x)+'\n') })) }));
return { statusCode: 200 };
};
5) Data Lake & Analytics (optional but powerful)
A) Firehose → S3 JSON → Athena Table (DDL)
CREATE EXTERNAL TABLE IF NOT EXISTS ses_events (
type string,
mailMessageId string,
timestamp string,
source string,
sesSourceIp string,
tags map<string, array<string>>,
email string,
detail string
)
PARTITIONED BY (dt string)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION 's3://your-bucket/ses-events/';
-- Load the dt=YYYY-MM-DD partitions (or use partition projection)
MSCK REPAIR TABLE ses_events;
Partition by dt=YYYY-MM-DD in your Firehose prefix for cost/perf.B) Sample Queries
- Daily bounce/complaint rate by config set:
SELECT dt,
tags['ses:configuration-set'][1] AS config_set,
CAST(SUM(CASE WHEN type = 'Bounce' THEN 1 ELSE 0 END) AS double)
/ NULLIF(SUM(CASE WHEN type IN ('Delivery', 'Bounce') THEN 1 ELSE 0 END), 0) AS bounce_rate,
CAST(SUM(CASE WHEN type = 'Complaint' THEN 1 ELSE 0 END) AS double)
/ NULLIF(SUM(CASE WHEN type = 'Delivery' THEN 1 ELSE 0 END), 0) AS complaint_rate
FROM ses_events
GROUP BY 1, 2
ORDER BY dt DESC;
- Top bouncing domains:
SELECT dt, regexp_extract(email, '@(.+)$') AS domain, COUNT(*) AS bounces
FROM ses_events
WHERE type='Bounce'
GROUP BY 1, 2
ORDER BY bounces DESC
LIMIT 50;
Best Practices & Guardrails
- List hygiene: Remove hard bounces and complainants immediately (suppression).
- Warm-up: Gradually increase volume from new IPs/domains.
- Authentication: DKIM/SPF/DMARC mandatory; align From & DKIM.
- Segmentation: Separate transactional vs marketing traffic via Configuration Sets and/or IP pools.
- Tagging: Add
EmailTags(e.g.,app,env,tenant,campaign) for measurable slices. - Content: Avoid spammy patterns; personalize & throttle.
- Alarms: Monitor rates, not only counts. Include opens/clicks to catch deliverability dips.
Challenges
- Verify a domain and send an email using SES CLI.
- Set up bounce and complaint notifications via SNS.
- Create a Lambda function that logs bounce events to CloudWatch.
- Send an email using Python (boto3) or Node.js (aws-sdk) programmatically.
- Configure SES with DKIM and SPF, and test delivery reputation.
- Implement bulk email sending with templates and configuration sets.
- Store inbound emails in an S3 bucket using SES rule sets.
🤷🏻 How to Participate?
✅ Complete the tasks and challenges.
✅ Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
✅ Share the above in a LinkedIn post tagging me (Sandip Das), and use #90DaysOfCloud to engage with the community!
⚡ Quick Reference
Keep the momentum going — everything you need on LearnXOps in one place:
- 🎓 Courses — Video courses & AI-built courses
- 📚 Ebooks — Community ebooks & your own
- 🧪 All Labs & Challenges — DevOps, Cloud, SRE & more
- ☸️ Kubernetes Labs & Playground — kind clusters, playground & challenges
- 🤖 AI Agent & Bot Labs — OpenClaw · Hermes · CrewAI · LangGraph · MCP

Member discussion