Polski

Tutorial · AWS SES · Authentication

Amazon SES in practice – domain verification (DKIM, SPF, DMARC), leaving the sandbox, sending via API and SMTP, templates, bounces and deliverability (Node.js, C#, Python)

We send the pierogi shop's e-mails with Amazon SES – a domain identity with Easy DKIM, a custom MAIL FROM domain for SPF, rolling out DMARC, leaving the sandbox, sending via the v2 API with AWS SDK v3 (text, templates, attachments) and via SMTP/Nodemailer, a configuration set with suppression, handling bounces and complaints through SNS and SQS, and deliverability rules. Variants in C# and Python.

By · · 25 min read

The verification link from the authentication tutorial has to reach the inbox, not the spam folder. So does the pierogi order confirmation. Amazon SES sends mail cheaply and reliably, but it will not do for you what decides deliverability: authenticating the domain, reacting to bounces and complaints, and treating recipients sensibly. In this tutorial you go the whole way – from DNS records to handling feedback – with code in Node.js, C# and Python.

Prerequisites: an AWS account, a domain with DNS access (Route 53 or any provider), Node.js 22+, the basics of SQS (queues, DLQ, Lambda). For the variants: .NET 10 SDK or Python 3.10+.

200
messages per day in the sandbox – 1 per second, verified recipients only
3
CNAME records – Easy DKIM
0.1%
complaints – account review threshold – at 0.5% SES may pause sending
5%
bounces – account review threshold – at 10% SES may pause sending
Diagram: Sending and the feedback loop: from the API to the inbox and back

SPF, DKIM and DMARC in five minutes

MechanismWhat it checksHow it looks in SES
SPFwhether the sending server may send mail for the envelope domain (MAIL FROM, the return path)a custom MAIL FROM domain (mail.pierogarnia.example) with v=spf1 include:amazonses.com ~all
DKIMa cryptographic signature of the message with the key of the From header's domainEasy DKIM: SES manages the keys, you add 3 CNAME records
DMARCwhether SPF or DKIM passed for the same domain as in From (alignment) and what to do if nota _dmarc record with a p=none/quarantine/reject policy and a report address

By default SES sends with an amazonses.com envelope – SPF passes, but for Amazon's domain, so it is not aligned with your From. DMARC then passes only thanks to DKIM. A custom MAIL FROM domain aligns both mechanisms – especially important with strict DMARC (aspf=s).

Since February 2024 Gmail and Yahoo require bulk senders (for Gmail: more than 5,000 messages a day) to have SPF, DKIM and DMARC, domain alignment, one-click unsubscribe (RFC 8058) in marketing messages and a spam rate below 0.3%. Microsoft introduced similar rules for Outlook.com in 2025. Even if you send less – meet them, because they decide whether you land in the inbox.

Step 1. The project

npm install @aws-sdk/client-sesv2 nodemailer zod
npm install -D typescript tsx vitest @types/node @types/nodemailer @types/aws-lambda

Project configuration

package.json
{
  "name": "pierogi-ses",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=22.12" },
  "scripts": {
    "ses:setup": "tsx --env-file-if-exists=.env src/setup.ts",
    "send:demo": "tsx --env-file-if-exists=.env src/send-demo.ts",
    "build": "tsc -p tsconfig.build.json",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  },
  "dependencies": {
    "@aws-sdk/client-sesv2": "^3.1178.0",
    "nodemailer": "^10.6.1",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.164",
    "@types/node": "^24.19.4",
    "@types/nodemailer": "^8.0.2",
    "tsx": "^4.23.15",
    "typescript": "^7.0.2",
    "vitest": "^5.1.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["src", "test"]
}
tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": { "noEmit": false, "rootDir": "src", "outDir": "dist" },
  "include": ["src"]
}
.env.example
AWS_REGION=eu-central-1
MAIL_DOMAIN=pierogarnia.example
MAIL_FROM="Pierogarnia Haliny <zamowienia@pierogarnia.example>"
MAIL_REPLY_TO=kontakt@pierogarnia.example
SES_CONFIGURATION_SET=pierogi-transactional
SES_EVENTS_TOPIC_ARN=arn:aws:sns:eu-central-1:123456789012:ses-events
# Only for the SMTP variant – generated in the SES console (not your IAM secret key!)
SMTP_USER=
SMTP_PASSWORD=
src/config.ts
import { z } from 'zod';

const EnvSchema = z.object({
  AWS_REGION: z.string().default('eu-central-1'),
  MAIL_DOMAIN: z.string().min(3),
  MAIL_FROM: z.string().min(3), // "Display Name <address@verified-domain>"
  MAIL_REPLY_TO: z.email().optional(),
  SES_CONFIGURATION_SET: z.string().default('pierogi-transactional'),
  SES_EVENTS_TOPIC_ARN: z.string().startsWith('arn:aws:sns:').optional(),
  SMTP_USER: z.string().optional(),
  SMTP_PASSWORD: z.string().optional(),
});

export type Config = z.infer<typeof EnvSchema>;
export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => EnvSchema.parse(env);

We use the SESv2 API (@aws-sdk/client-sesv2) – newer and more complete than the classic @aws-sdk/client-ses. New features (contact lists, suppression list management, VDM) appear in v2.

Step 2. Domain identity, configuration set and templates

Setup script and templates

src/setup.ts
import {
  AlreadyExistsException,
  CreateConfigurationSetCommand,
  CreateConfigurationSetEventDestinationCommand,
  CreateEmailIdentityCommand,
  CreateEmailTemplateCommand,
  PutAccountDetailsCommand,
  PutEmailIdentityMailFromAttributesCommand,
  SESv2Client,
} from '@aws-sdk/client-sesv2';
import { loadConfig } from './config.js';
import { TEMPLATES } from './templates.js';

const config = loadConfig();
const ses = new SESv2Client({ region: config.AWS_REGION });
const domain = config.MAIL_DOMAIN;
const mailFrom = `mail.${domain}`;

// Re-runnable: "already exists" is fine.
async function ignoreExisting(step: string, action: () => Promise<unknown>) {
  try {
    await action();
    console.info(`✓ ${step}`);
  } catch (err) {
    if (err instanceof AlreadyExistsException) console.info(`= ${step} (already exists)`);
    else throw err;
  }
}

// 1. Configuration set: reputation metrics, suppression, TLS required, events to SNS.
await ignoreExisting('configuration set', () =>
  ses.send(
    new CreateConfigurationSetCommand({
      ConfigurationSetName: config.SES_CONFIGURATION_SET,
      ReputationOptions: { ReputationMetricsEnabled: true },
      SuppressionOptions: { SuppressedReasons: ['BOUNCE', 'COMPLAINT'] },
      DeliveryOptions: { TlsPolicy: 'REQUIRE' },
    }),
  ),
);
if (config.SES_EVENTS_TOPIC_ARN) {
  await ignoreExisting('event destination -> SNS', () =>
    ses.send(
      new CreateConfigurationSetEventDestinationCommand({
        ConfigurationSetName: config.SES_CONFIGURATION_SET,
        EventDestinationName: 'feedback-to-sns',
        EventDestination: {
          Enabled: true,
          MatchingEventTypes: ['BOUNCE', 'COMPLAINT', 'REJECT', 'DELIVERY', 'DELIVERY_DELAY', 'RENDERING_FAILURE'],
          SnsDestination: { TopicArn: config.SES_EVENTS_TOPIC_ARN },
        },
      }),
    ),
  );
}

// 2. Domain identity with Easy DKIM: SES generates and manages the 2048-bit keys.
let dkimTokens: string[] = [];
await ignoreExisting('domain identity', async () => {
  const res = await ses.send(
    new CreateEmailIdentityCommand({
      EmailIdentity: domain,
      DkimSigningAttributes: { NextSigningKeyLength: 'RSA_2048_BIT' },
      ConfigurationSetName: config.SES_CONFIGURATION_SET, // default set for this identity
    }),
  );
  dkimTokens = res.DkimAttributes?.Tokens ?? [];
});

// 3. Custom MAIL FROM domain: SPF aligned with our domain (needed for strict DMARC).
await ses.send(
  new PutEmailIdentityMailFromAttributesCommand({
    EmailIdentity: domain,
    MailFromDomain: mailFrom,
    BehaviorOnMxFailure: 'USE_DEFAULT_VALUE',
  }),
);

// 4. Templates.
for (const [name, content] of Object.entries(TEMPLATES)) {
  await ignoreExisting(`template ${name}`, () =>
    ses.send(new CreateEmailTemplateCommand({ TemplateName: name, TemplateContent: content })),
  );
}

console.info('\nAdd these DNS records:');
for (const token of dkimTokens) console.info(`${token}._domainkey.${domain}  CNAME  ${token}.dkim.amazonses.com`);
console.info(`${mailFrom}  MX  10 feedback-smtp.${config.AWS_REGION}.amazonses.com`);
console.info(`${mailFrom}  TXT  "v=spf1 include:amazonses.com ~all"`);
console.info(`_dmarc.${domain}  TXT  "v=DMARC1; p=none; rua=mailto:dmarc@${domain}"`);

// 5. Leaving the sandbox (run once, after DNS is verified). AWS reviews the request.
export async function requestProductionAccess(): Promise<void> {
  await ses.send(
    new PutAccountDetailsCommand({
      MailType: 'TRANSACTIONAL',
      WebsiteURL: `https://${domain}`,
      ContactLanguage: 'EN',
      UseCaseDescription:
        'Order confirmations, invoices, e-mail verification and password reset for customers of an online pierogi shop. ' +
        'Recipients sign up themselves; bounces and complaints are processed automatically via SNS and suppressed.',
      ProductionAccessEnabled: true,
    }),
  );
}
src/templates.ts
import type { EmailTemplateContent } from '@aws-sdk/client-sesv2';

// SES templates use Handlebars-style placeholders, including {{#each}} and {{#if}}.
export const TEMPLATES: Record<string, EmailTemplateContent> = {
  'order-confirmation': {
    Subject: 'Order {{orderId}} is in the kitchen',
    Text: [
      'Hi {{customerName}},',
      '',
      'we have your order {{orderId}}:',
      '{{#each items}}- {{quantity}} x {{dish}}',
      '{{/each}}',
      'Total: {{total}} PLN. We will text you when it is ready.',
      '',
      "Halina's pierogi shop",
    ].join('\n'),
    Html: [
      '<p>Hi {{customerName}},</p>',
      '<p>we have your order <strong>{{orderId}}</strong>:</p>',
      '<ul>{{#each items}}<li>{{quantity}} &times; {{dish}}</li>{{/each}}</ul>',
      '<p>Total: <strong>{{total}} PLN</strong>. We will text you when it is ready.</p>',
      "<p>Halina's pierogi shop</p>",
    ].join(''),
  },
};

The order in the script makes sense:

  1. The configuration set groups sending settings: reputation metrics, suppressing addresses after bounces and complaints, enforced TLS (TlsPolicy: 'REQUIRE' – SES will not deliver to a server without TLS) and the event destination – an SNS topic for bounces, complaints, rejects, deliveries, delays and rendering failures.
  2. The domain identity with Easy DKIM and a 2048-bit key. With a verified domain you can send from any address in it (orders@, account@). A default configuration set attached to the identity applies even when someone forgets to pass it to SendEmail.
  3. The MAIL FROM domain – a subdomain that receives bounces and authenticates the envelope with SPF.
  4. Templates – the e-mail copy lives in SES, and the app only sends JSON data. The Handlebars syntax supports {{variables}}, {{#each}} and {{#if}}.

The script is idempotent: an AlreadyExistsException on a re-run means "already there". In a real project you describe the same resources in Terraform or CDK.

Step 3. DNS records and permissions

DNS records and the sender IAM policy

infra/dns-records.txt
; DNS records for pierogarnia.example (values printed by `npm run ses:setup`)

; Easy DKIM: three CNAMEs pointing at keys managed by SES, which signs every message
tok1abc._domainkey.pierogarnia.example.   CNAME  tok1abc.dkim.amazonses.com.
tok2def._domainkey.pierogarnia.example.   CNAME  tok2def.dkim.amazonses.com.
tok3ghi._domainkey.pierogarnia.example.   CNAME  tok3ghi.dkim.amazonses.com.

; Custom MAIL FROM: bounces go to SES, SPF passes for OUR domain (alignment for DMARC)
mail.pierogarnia.example.   MX   10 feedback-smtp.eu-central-1.amazonses.com.
mail.pierogarnia.example.   TXT  "v=spf1 include:amazonses.com ~all"

; DMARC: start with p=none and reports, move to quarantine/reject once reports are clean
_dmarc.pierogarnia.example. TXT  "v=DMARC1; p=none; rua=mailto:dmarc-reports@pierogarnia.example; adkim=s; aspf=s"

; If the root domain also sends from Google Workspace / Microsoft 365, keep ONE SPF record there:
; pierogarnia.example.  TXT  "v=spf1 include:_spf.google.com ~all"
infra/iam-sender-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "SendTransactionalMailOnly",
      "Effect": "Allow",
      "Action": "ses:SendEmail",
      "Resource": [
        "arn:aws:ses:eu-central-1:123456789012:identity/pierogarnia.example",
        "arn:aws:ses:eu-central-1:123456789012:configuration-set/pierogi-transactional",
        "arn:aws:ses:eu-central-1:123456789012:template/order-confirmation"
      ],
      "Condition": {
        "StringLike": { "ses:FromAddress": "*@pierogarnia.example" }
      }
    }
  ]
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 4. Leaving the sandbox
  • Step 5. Sending via the v2 API
  • Step 6. SMTP and Nodemailer
  • Step 7. Bounces and complaints
  • Step 8. Tests and the mailbox simulator
  • C# and Python variants
  • Deliverability – a checklist
  • Costs
  • Common mistakes
  • Check yourself
  • What's next

Create a free account · Sign in