Direct mail for growth teams, with an API underneath. Read the docs →

Direct mail API for AWS

Direct mail API for AWS: your app puts a message on an SQS queue when an order is paid or a charge fails, one Lambda function sends it to Mailr with the key from Secrets Manager, and EventBridge Scheduler starts a nightly job that queues win-back batches.

What to mail from AWS

When this happensMail this
Your app sends an SQS message when an order is paidA thank-you postcard for a first order. (First-order thank you)
EventBridge Scheduler runs the nightly function at 2:00 a.m. (America/Phoenix)Win-back postcards to customers 60+ days past their last order, one batch per 1,000. (Win-back)
Your billing code sends a message after the third failed chargeA plain billing letter, mailed flat. (Failed payment)

Set it up

  1. Store the key in Secrets Manager. Create a secret named mailr/api-key holding your mlr_test_ key, and give the sender's execution role secretsmanager:GetSecretValue on it. A Parameter Store SecureString works too: read it with getParameter from @aws-lambda-powertools/parameters/ssm and decrypt: true, which needs ssm:GetParameter and kms:Decrypt.
  2. Create the queue and its dead-letter queue. Make mailr-send with a 180-second visibility timeout (six times the sender's 30-second timeout, as AWS recommends) and a redrive policy that moves a message to mailr-send-dlq after 5 receives.
  3. Deploy the sender. sender.mjs on the nodejs24.x runtime with a 30-second timeout and the AWSLambdaSQSQueueExecutionRole policy. Map the queue to it with ReportBatchItemFailures turned on, so only the messages that failed go back on the queue.
  4. Deploy the nightly job and its schedule. nightly.mjs needs sqs:SendMessage on the queue and the queue URL in MAILR_QUEUE_URL. The schedule's execution role needs lambda:InvokeFunction on the function. Save your return address in Mailr's Settings so the messages can leave out from.
  5. Send from your app, then go live. Anything that should mail puts { path, idempotencyKey, body } on the queue, with the key built from your record id (thank-you-<order id>). Test pieces show up in the Mailr dashboard and never print. To go live, put your mlr_live_ key in the secret; the sender picks it up within its 5-minute cache.

Lambda functions and setup

// sender.mjs: Lambda (nodejs24.x) with an SQS trigger and ReportBatchItemFailures turned on.
// npm install @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager
import { getSecret } from "@aws-lambda-powertools/parameters/secrets";

// Each message: { "path": "/postcards" | "/flats" | "/batches", "idempotencyKey": "...", "body": { ...Mailr request } }
const PERMANENT = [400, 401, 404, 422]; // a retry can't fix these

export const handler = async (event) => {
  const apiKey = await getSecret("mailr/api-key", { maxAge: 300 }); // cached for 5 minutes
  const batchItemFailures = [];

  for (const record of event.Records) {
    try {
      const job = JSON.parse(record.body);
      const res = await fetch(`https://api.mailr.dev/v1${job.path}`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
          "Idempotency-Key": job.idempotencyKey, // a redelivered message gets the first piece back
        },
        body: JSON.stringify(job.body),
        signal: AbortSignal.timeout(20_000),
      });
      const data = await res.json();

      if (res.ok) {
        // Store data.id (or data.pieces for a batch) where your app keeps it, for example on the order row.
        console.log(JSON.stringify({ key: job.idempotencyKey, mailr_id: data.id, replayed: res.headers.get("idempotent-replayed") === "true" }));
      } else if (PERMANENT.includes(res.status)) {
        console.error(JSON.stringify({ key: job.idempotencyKey, status: res.status, error: data.error }));
      } else {
        throw new Error(`Mailr ${res.status}: ${data.error?.message}`); // 402, 409, 5xx: try again later
      }
    } catch (err) {
      console.warn(record.messageId, err.message);
      batchItemFailures.push({ itemIdentifier: record.messageId });
    }
  }

  return { batchItemFailures };
};
  • SQS can deliver a message more than once, and Lambda retries the ones that fail. Each message carries an Idempotency-Key built from your record ids, so a repeat within 24 hours gets the first piece back, marked Idempotent-Replayed: true, instead of a second one.
  • Errors a retry can't fix (400, 401, 404, 422) are logged and dropped. A 402 (balance too low), 409 (the same key is still running), a 5xx or a timeout goes back on the queue and lands in mailr-send-dlq after 5 receives.
  • An SQS message can hold up to 1 MiB, enough for a 1,000-recipient batch body. Each batch is one request to Mailr and is all or nothing.
  • getSecret caches the key for the maxAge you pass, here 300 seconds. Without maxAge, Powertools caches for 5 seconds.
  • EventBridge Scheduler cron expressions have six fields, the last one the year, and need a ? in day-of-month or day-of-week. With a time zone set, the schedule follows daylight saving time; America/Phoenix has none.

What it costs

Each live piece is paid from your Mailr balance, printing and postage included: a 4x6 postcard is $0.85, a 6x9 $0.89 and an 8.5x11 letter $0.95 on pay as you go, less on a plan. Test pieces are free. All prices.

Templates that fit: First-order thank you (6x9), Win-back (6x11), Failed payment (8.5x11).

Questions

Why not call Mailr straight from the code that handles the order?

You can: it's one fetch with a Bearer key. The queue adds retries with backoff, a dead-letter queue for what still fails, and one place that holds the key, so the rest of your app never needs secretsmanager access.

Secrets Manager or Parameter Store?

Either works. AWS points to Secrets Manager for API keys that need rotation, cross-account access or audit logging. A Parameter Store SecureString is fine for one key; swap getSecret for getParameter with decrypt: true.

Can Mailr publish delivery events to EventBridge or SNS?

Not yet. Mailr has no webhooks or event feed, so read GET /v1/postcards/{id} when you need a status, or list one batch's pieces with GET /v1/postcards?batch=bat_...

Which Lambda runtime should I use?

Any Node.js runtime with built-in fetch. The examples use nodejs24.x, which AWS supports until April 2028. Other runtimes work the same way: one POST with the Bearer key and the Idempotency-Key header.

The code on this page is written against the Mailr API as it works today. Test it with your test key first; nothing prints until you use a live key.
AWS

Mail from AWS today

Get a free test key, send one postcard to yourself and watch it move through every status.

  • Postcards, flats and folded mailers
  • A proof before anything prints
  • Free test mode: nothing prints, nothing charges
  • A status for every piece

Download the template kit?

mailr-kit.zip · about 310 KB · 65 text files

Only HTML, JSON and Markdown files. No programs, scripts or macros, nothing that installs or runs.