Skip to content

Serverless Transactional Email: SES and Lambda

How SES becomes an event-driven email building block: outgoing confirmation emails from a Lambda Function and incoming Receipt Rules that turn an email into a handler call.

≈ 14 min readSoftwareAWSCloud

A SendEmail call carries up to 50 recipients and 10 MB of message. An incoming SES event carries zero bytes of email text: it delivers headers and metadata, and the body sits in S3. These two numbers say more about the service than any feature list – the outgoing direction is done in half an hour, the incoming one has its own rules that you need to know.

Behind this lies a decision that sounds like configuration to the team: “So how do we send out the confirmation email now?” Often there is already a signup flow, maybe with user management as in Serverless Auth with Cognito User Pools, and the email looks like the last, trivial building block. That is exactly where the mistake lies. The real question is: Do I treat email as an external Side Effect that I stick onto the end of a flow, or as a full domain event – in and out – that deserves the same treatment as an API call or a queue message?

This choice decides whether the email part later fits cleanly into the architecture or causes friction as a foreign body. SES – the Simple Email Service – is instructive because it serves both directions with the same building blocks: Lambda on one side, Receipt Rules on the other. The leverage is not in the API fields but in this symmetry. Below I walk through both directions – first the outgoing confirmation email from a function, then the incoming email hook that turns a real email into, for example, a support ticket. The code is deliberately lean so that the common thread – event in, event out – stays visible.

SES as a building block in two directions#

Before we write code, it pays to look at the mental model. SES sits at the system boundary between your application and the outside world of email. Outward: your app triggers an event – a new account, a paid order – and a Lambda Function calls SendEmail. Inward: someone sends an email to one of your addresses, and SES processes it further via so-called Receipt Rules, for example to S3, to SNS or directly to a Lambda Function.

This symmetry is the core. As soon as SES shows up in the design as an event-driven building block, it fits cleanly into the rest of the serverless architecture. If it stays a mere “email sender,” it ends up bolted on from the outside. The outgoing direction is the more common one and the easier place to start.

  • Outgoing: SendEmail or SendTemplatedEmail, a verified sender, sandbox and quota in view, triggered by an app event.
  • Incoming: a Receipt Rule Set with actions for S3, Lambda or SNS, available only in certain regions, triggered by an arriving email, body loaded afterward from S3.

Let’s keep these two lines in mind – they structure the rest of the article.

Email as a domain event, not as SES configuration#

The difference sounds academic, but it has real consequences. If you see SES as a configuration task, you stop at “sender verified, SendEmail works.” If you model email as a domain event, you keep asking: Which business event triggers this email, and which event does an arriving email create in my system? “I send a message” becomes “a signup happened,” and “someone emailed” becomes “a support case came in.” The email is then only the transport, not the event itself.

This perspective costs something and gives something. The price is extra care at the system boundary: verified identities, an active rule set, correct permissions, the knowledge that incoming bodies sit in S3. The return is connectability. An event can be passed on, orchestrated, logged and tested – a “sent email,” on the other hand, is a dead end.

A few decision criteria help with the question of whether SES is the right building block:

  • Coupling and control: SES stays entirely within AWS and IAM, with no second provider and no additional contract. In return, you carry the regional restriction on receiving and the MIME parsing yourself.
  • Cost: SES bills per thousand emails and costs nothing when idle. A specialized transactional provider brings better deliverability tools and ready-made templates, but also its own bill and a second system that someone has to operate.
  • Impact: Only when the incoming email is a real event can you automate the follow-up – classification, assignment, draft reply. That is exactly what shortens the cycles that otherwise depend on manual triage.

As long as email is an event source and sink inside an AWS architecture, SES is the choice with the least friction. As soon as marketing deliverability, bounce analytics and campaign tooling come to the fore, a dedicated provider is the more honest choice. For the transactional core – confirmation out, ticket in – the event-driven SES building block wins.

The outgoing confirmation email#

Let’s start with the outgoing direction. A Lambda Function is triggered by an event – say, an API Gateway call after a successful registration – and is supposed to send a short confirmation email.

The following diagram shows the path of the event. The event comes in, the Lambda Function translates it into a SendEmail call, and SES accepts the message. That is not yet a delivery guarantee: bounces and complaints run through their own SES events. If the triggering event is repeated, the email can also be sent twice. For a production flow, I therefore need a stable event key and a stored sending status or an outbox.

flowchart LR
  A[Event: Signup] --> B[Lambda: sendConfirmationEmail]
  B --> C[ses:SendEmail]
  C --> D[Recipient Inbox]

The corresponding handler is manageable. Here I use the AWS SDK for JavaScript version 3, that is, the modular @aws-sdk/client-ses packages – the established version 2 with new AWS.SES() works just as well, but for new functions its import is simply too monolithic for my taste.

import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";

const ses = new SESClient({ region: "eu-west-1" });

export async function sendConfirmationEmail(event: {
  email: string;
  name: string;
}) {
  const command = new SendEmailCommand({
    Source: "no-reply@example.com",
    Destination: {
      ToAddresses: [event.email],
    },
    Message: {
      Subject: {
        Data: "Willkommen bei uns",
        Charset: "UTF-8",
      },
      Body: {
        Html: {
          Data: `<p>Hallo ${event.name}, dein Konto ist aktiv.</p>`,
          Charset: "UTF-8",
        },
      },
    },
  });

  const result = await ses.send(command);
  return { messageId: result.MessageId };
}

Three things are mandatory here and therefore deserve a closer look. Source is the sender address and must be a 7-bit ASCII address of a verified identity. Destination groups the recipients into ToAddresses, CcAddresses and BccAddresses. Message carries Subject and Body, where the body can contain text and HTML, each as an object of Data and Charset. What comes back is a MessageId – the only receipt you get for a successful call. Optionally, you can add quite a bit more, such as ReplyToAddresses or a ConfigurationSetName, but for the confirmation email what is shown is enough.

Verified senders, sandbox and quota#

The code is rarely the stumbling block. There are three organizational points you need to settle beforehand.

First, the sender identity. SES only sends from verified senders. You can verify a single address or – much more sensible for production – an entire domain via DKIM and TXT records in DNS. If the sender is not verified, SES answers the call with “Email address not verified,” and the email does not go out.

Second, the sandbox. Every new SES account starts in the sandbox. That means you may only send to verified recipients or to the SES Mailbox Simulator, and the sending quota is reduced. The confirmation email to a real customer therefore fails in the sandbox as long as their address is not verified itself. For production use, you have to request production access via a support case.

Third, the quota. Every recipient of a message counts against your sending allowance. A SendEmail call may address at most 50 recipients across To, Cc and Bcc combined, and the message may be up to 10 MB in size.

For demos and tests, the Mailbox Simulator is worth its weight in gold. A call to success@simulator.amazonses.com behaves like a successful delivery, without you running into sandbox limits or burdening real mailboxes.

Templates instead of string concatenation#

As soon as more than one kind of email is involved, assembling HTML in code gets messy. SES offers server-side templates for this. You create a template once with CreateTemplate – with SubjectPart, TextPart and HtmlPart, containing placeholders in double curly braces – and then send with SendTemplatedEmail.

import { SESClient, SendTemplatedEmailCommand } from "@aws-sdk/client-ses";

const ses = new SESClient({ region: "eu-west-1" });

export async function sendWelcome(email: string, name: string) {
  const command = new SendTemplatedEmailCommand({
    Source: "no-reply@example.com",
    Destination: { ToAddresses: [email] },
    Template: "WelcomeTemplate",
    TemplateData: JSON.stringify({ name }),
  });

  return ses.send(command);
}

TemplateData is a JSON string whose keys fill the placeholders in the template. The advantage: the text no longer lives in the deployment artifact but sits as a resource in SES and can be updated independently of the code. For many recipients at once, there is also SendBulkTemplatedEmail – in a transactional context, though, you rarely need it, because there one email usually goes to one person.

The incoming email hook#

Now we reverse the direction. The second, often overlooked capability of SES: it can receive arriving emails and turn them into an event in your architecture. This is the basis for patterns such as “an email to support@ automatically becomes a ticket.”

This is managed through a Receipt Rule Set. There can be several rule sets per account, but only one is ever active. Inside a rule set, you define individual Receipt Rules that match certain recipient addresses and work through a list of actions. Available actions include: storing in an S3 bucket, publishing to an SNS topic, invoking a Lambda Function, adding a header, a bounce or a stop.

The usual setup for a ticket flow combines two actions: first the raw email is written to S3, then a Lambda Function is triggered that takes care of the processing.

flowchart LR
  A[Incoming Mail] --> B[SES Receipt Rule]
  B --> C[S3: raw MIME]
  B --> D[Lambda: handleInboundEmail]
  D --> E[Ticket / DB]
  B -.-> F[SNS Notification]

The Receipt Rule as infrastructure#

The Receipt Rule itself belongs in Infrastructure as Code, not in a console setup clicked together by hand – otherwise it is gone after the next account switch. As a sketch in CloudFormation-like form, a rule looks roughly like this:

Resources:
  SupportRule:
    Type: AWS::SES::ReceiptRule
    Properties:
      RuleSetName: default-rule-set
      Rule:
        Name: support-inbound
        Enabled: true
        Recipients:
          - support@example.com
        Actions:
          - S3Action:
              BucketName: inbound-mail-bucket
          - LambdaAction:
              FunctionArn: !GetAtt InboundFn.Arn
              InvocationType: Event

Two details matter here. The order of the actions counts: the email must first be in S3, then the Lambda Function that reads it from there is called. And InvocationType: Event means an asynchronous call – that is the recommended variant. The synchronous RequestResponse call also exists, but it has a hard timeout of 30 seconds and lets the Lambda Function control the rest of the rule flow through its return value, for example with { disposition: "STOP_RULE" }. For a ticket handler that does not want to control the email flow anyway, Event is the right choice.

The handler and the most common mistake#

Let’s get to the handler – and to the pitfall that strikes most reliably in projects. The obvious assumption is that the Lambda event contains the email text. It does not. The event that SES passes to the Lambda Function carries only metadata and headers – sender, subject, message ID – but not the body. The complete MIME content lands in S3, and the handler has to load it from there.

The event is built around a Records array, with eventSource: "aws:ses" and the fields ses.receipt and ses.mail. The latter contains the processed headers under commonHeaders and, under messageId, the key under which the raw email sits in S3.

import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { Readable } from "stream";

const s3 = new S3Client({ region: "eu-west-1" });

async function streamToString(stream: Readable): Promise<string> {
  const chunks: Buffer[] = [];
  for await (const chunk of stream) {
    chunks.push(Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString("utf-8");
}

export async function handleInboundEmail(event: any) {
  const record = event.Records[0];
  const mail = record.ses.mail;
  const messageId = mail.messageId;

  const raw = await s3.send(
    new GetObjectCommand({
      Bucket: "inbound-mail-bucket",
      Key: messageId,
    })
  );

  const mime = await streamToString(raw.Body as Readable);

  // parse MIME, then create a support ticket
  await createTicket({
    from: mail.commonHeaders.from?.[0],
    subject: mail.commonHeaders.subject,
    body: mime,
  });

  return { status: "processed" };
}

I deliberately left out the actual MIME parsing here – you use a library for that, because parsing multipart emails with attachments by hand is not a good idea. The point is the flow: headers from the event, body from S3, then the business action. The S3 object can be up to 40 MB in size.

Permissions and DNS, or nothing happens, silently#

The second pitfall on the receiving side is unspectacular and therefore treacherous: without the right permissions, SES simply and silently does not process arriving email. SES needs a resource policy that allows it to write to the S3 bucket, publish to the SNS topic or invoke the Lambda Function. If one of these permissions is missing, there is no loud error message – the email just seeps away.

Then there is DNS. For email to reach SES at all, the MX records of your domain must point to inbound-smtp.<region>.amazonaws.com. And there is a hard regional restriction: SES offers email receiving only in selected regions – as of today us-east-1, us-west-2 and eu-west-1. Lambda and SNS for the incoming flow must be in the same region as the SES endpoint. If you run the rest of your infrastructure in a different region, you have to move this part there deliberately.

Where SES fits into the larger architecture#

Together, the two directions make a nice picture: Lambda is the shared compute core, SES the system boundary to the world of email. Outward, a function translates app events into emails; inward, SES translates arriving emails into function calls.

It gets interesting when the incoming hook is not the end but the beginning of a longer processing chain. A support email that gets parsed can kick off a chain of steps – classification, assignment, draft reply. This is exactly where orchestration is worth a look, as I described it in Serverless Workflows with AWS Step Functions: the SES Lambda creates the ticket and hands over to a State Machine that coordinates the rest. That way the email hook stays small and does exactly one thing, while the domain logic gets its own traceable flow.

Conclusion#

The aha moment with SES lies in the incoming direction: when it becomes clear that arriving email is not a special case but an entirely normal event trigger – just like an API call or a queue message. The outgoing side is quickly explained: verified sender, SendEmail or a template, keep sandbox and quota in mind. The incoming side needs more care: an active rule set, the right permissions, MX records and the knowledge that the body sits in S3 and not in the event.

The gain from this perspective is concrete. Shorter cycles, because an incoming email hook kicks off follow-up work instead of parking it in a mailbox. Less friction, because email follows the same event-driven rules as the rest of the architecture and does not stand beside it as a foreign body. Higher quality, because a modeled event is testable, loggable and orchestratable, where a loosely sent email remains a dead end. And clear limits: as soon as deliverability at scale, bounce analytics or campaigns come to the fore, a specialized provider is the more honest choice – SES shines in the transactional core. Once you have built these two patterns cleanly, you no longer think “how do I send an email” but “email is simply another event source and sink” – in and out.

Further reading#

Revised and translated from German with the help of AI.