Hoppa till innehållet

Frameworks

Express

The TypeScript SDK, @sendora/sdk, sends an Express app’s mail, and checks each webhook’s signature against the raw body. This guide’s samples run on Express 4 and 5. They are TypeScript, which Node 22.18 and newer run as it is.

Before you start

  • A server key, which you create on the server’s API keys tab in the dashboard. A test server’s key works before Sendora approves your account, and it delivers nothing.
  • A verified sending domain for the From address. A test server checks the domain too.

Install

npm install @sendora/sdk express
npm install --save-dev @types/express

The samples are ES modules, so set "type": "module" in package.json. Node runs their TypeScript as it is, so each import names its file in full, .ts included.

Settings

Set the server key and the webhook’s secret in .env, and keep the file out of git. You get the secret once you create the webhook, as Webhooks below shows.

SENDORA_API_TOKEN=sk_…
SENDORA_WEBHOOK_SECRET=whsec_…

SENDORA_API_TOKEN is the server key, and SENDORA_WEBHOOK_SECRET the webhook’s signing secret.

Make the client once, in src/sendora.ts. The SDK throws when the key is missing, so the app stops as it starts rather than at its first send.

import { Sendora } from '@sendora/sdk';

export const sendora = new Sendora({
  token: process.env.SENDORA_API_TOKEN,
});

Mount the routers in src/app.ts, which the sections below write. The webhook’s router comes first, since express.json() would parse the webhook’s body before its signature is checked:

import express from 'express';
import { contact } from './contact.ts';
import { webhooks } from './webhooks.ts';

export const app: express.Express = express();

// Before express.json(), which would parse the webhook's
// body before its signature is checked.
app.use(webhooks);
app.use(express.json());
app.use(contact);

Then start the app in src/server.ts. It refuses a test key in production, as Develop against a test server explains:

import { isTestKey } from '@sendora/sdk';
import { app } from './app.ts';

const token = process.env.SENDORA_API_TOKEN ?? '';
if (
  process.env.NODE_ENV === 'production' &&
  isTestKey(token)
) {
  throw new Error(
    'SENDORA_API_TOKEN is a test key; ' +
      'nothing would be delivered',
  );
}

const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => {
  console.log('Listening on port', port);
});

Run it with node --env-file=.env src/server.ts. In production, set the variables in the environment instead, and NODE_ENV to production.

Send mail

The route in src/contact.ts sends a contact form’s message to your support address:

import express from 'express';
import { sendora } from './sendora.ts';

export const contact: express.Router = express.Router();

contact.post('/contact', async (req, res, next) => {
  // Express 5 leaves the body undefined without JSON.
  const { email, message } = (req.body ?? {}) as {
    email?: unknown;
    message?: unknown;
  };
  if (
    typeof email !== 'string' ||
    typeof message !== 'string'
  ) {
    res
      .status(400)
      .json({ error: 'Send an address and a message.' });
    return;
  }

  try {
    const { messageId } = await sendora.email.send({
      from: {
        email: 'no-reply@example.se',
        name: 'Example AB',
      },
      to: ['support@example.se'],
      headers: { 'Reply-To': email },
      subject: 'A message from the contact form',
      text: message,
      tag: 'contact-form',
    });
    res.status(202).json({ messageId });
  } catch (error) {
    next(error);
  }
});
  • The route sends to your own address, and takes the visitor’s only for Reply-To. A route that sends to an address from its request would let anyone mail anyone.
  • Sendora refuses a header value that holds a line break, so the visitor’s address cannot add a header of its own.
  • The route takes the form as JSON, which express.json() parses. For a plain HTML form, mount express.urlencoded({ extended: false }) beside it.
  • send() returns the accepted message, with Sendora’s messageId, which the log and the webhooks use.
  • The tag sets the form’s mail apart in the log and in every webhook. Add metadata for ids of your own, such as an order’s.
  • If Sendora refuses the mail, send() throws a SendoraError with the error code. Express’s own error handler answers with the error’s status, the one Sendora answered, such as 422. An error handler of your own can answer otherwise.
  • Express 5 hands a rejected promise to the error handler, and Express 4 does not. So the route catches the error and passes it to next(), which works on both.
  • When a job may send the same mail twice, pass an idempotency key of your own, as in sendora.email.send(email, { idempotencyKey: 'order-1042-shipped' }). A retry with the same key returns the first answer and sends nothing.

Webhooks

The webhook’s router checks each delivery’s signature, then handles its event. A delivery is one post of one event to your webhook.

  1. Add the router, src/webhooks.ts. This one logs a hard bounce, and files each received mail as Received mail explains:
import {
  SendoraError,
  verifyWebhook,
} from '@sendora/sdk';
import express from 'express';
import { fileTicket } from './tickets.ts';

export const webhooks: express.Router = express.Router();

webhooks.post(
  '/sendora/webhook',
  // The signature covers the body as Sendora sent it.
  express.raw({ type: 'application/json' }),
  async (req, res, next) => {
    try {
      const event = await verifyWebhook({
        secret: process.env.SENDORA_WEBHOOK_SECRET,
        signature: req.get('sendora-signature'),
        body: req.body as Buffer,
      }).catch((error: unknown) => {
        if (error instanceof SendoraError) {
          return null;
        }
        throw error;
      });
      if (event === null) {
        res.sendStatus(400);
        return;
      }

      if (
        event.event === 'bounced' &&
        event.details.hard
      ) {
        console.warn(
          'A message bounced for good',
          event.messageId,
        );
      } else if (event.event === 'inbound') {
        await fileTicket(event.inboundMessageId);
      }
      res.sendStatus(204);
    } catch (error) {
      next(error);
    }
  },
);
  1. Create a webhook under the server’s Webhooks tab, with the address of the route, such as https://example.se/sendora/webhook. If the app receives mail, create it through the API instead, as Received mail says.
  2. Put its secret in SENDORA_WEBHOOK_SECRET, and deploy.

express.raw() hands the route the body as Sendora sent it, a Buffer, and verifyWebhook() checks the signature before it parses anything. It returns the event, typed by its name in event.event, so event.details has that event’s fields. Webhooks says when Sendora sends each event, and Webhook events lists their fields.

  • The route answers 204 once it has handled the event. If the handling throws, Express’s error handler answers with an error, and Sendora delivers the event again later, on the schedule that Webhooks gives.
  • Sendora waits only as long as Limits says, so queue slow work.
  • A delivery whose signature is missing, wrong or more than five minutes old gets 400, since verifyWebhook() throws a SendoraError with invalid_signature or stale_signature. Without the secret, it throws a TypeError, and the route answers 500.
  • A delivery can arrive more than once. Key your handling on event.id, the delivery’s id, which stays the same on each attempt.
  • express.raw() answers 413 to a body over 100 KB, and so to each retry of it. An inbound event that carries the whole mail can be larger, as Limits shows, so create the webhook for received mail as the next section says.
  • If the app checks a CSRF token or a session before its routes, mount the webhook’s router before that too. Sendora sends neither.
  • To roll the secret, create the new one and set SENDORA_WEBHOOK_SECRET to it. Sendora signs each delivery with both until you delete the old one.

Received mail

The router above files each received mail. An inbound event has the message’s inboundMessageId, and src/tickets.ts fetches the mail by it:

import { mkdir, writeFile } from 'node:fs/promises';
import { sendora } from './sendora.ts';

export async function fileTicket(
  inboundMessageId: string,
) {
  const mail = await sendora.inbound.get(
    inboundMessageId,
  );

  // Only a DMARC pass proves who sent it.
  const folder =
    mail.authentication.dmarc === 'pass'
      ? 'tickets'
      : 'tickets/unverified';
  await mkdir(folder, { recursive: true });
  await writeFile(
    `${folder}/${inboundMessageId}.txt`,
    mail.text ?? '',
  );
}
  • The route fetches the mail, so create its webhook through the API with inboundContent set to reference, as in sendora.webhooks.create({ url, inboundContent: 'reference' }). A webhook from the dashboard carries the whole mail in each inbound event, as Inbound explains.
  • Only a DMARC pass proves that the From domain sent the message. With any other verdict, the From address may be forged.
  • Sendora keeps the mail’s content for the stream’s retention, as Inbound says. After that, the route finds its text null.
  • A test server has no inbound stream, so receive mail on a live server.

Develop against a test server

A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with sk_test_.

  1. Create a test server under Servers › New server, with Testserver ticked, and a key on its API keys tab.
  2. Put the key in SENDORA_API_TOKEN in .env on your machine, and in CI. Keep a live server’s key in production.
  3. Send to the simulator’s addresses, such as hardbounce@simulator.sendora.se, to act out a bounce or a complaint. The message’s events show in the dashboard’s message log, as Messages and events explains.

src/server.ts above refuses a test key where mail must arrive. With NODE_ENV set to production, the app stops before it listens. If a staging server runs in production mode with a test key, base the check on a variable that you set in production alone, such as APP_ENV=production.

Sendora posts webhooks only to a public HTTPS address, so a test server’s events cannot reach your machine. Post a signed delivery to the route yourself instead. With the app running, scripts/try-webhook.ts posts a hard bounce, signed as Verify the signature describes:

import { createHmac, randomUUID } from 'node:crypto';

const body = JSON.stringify({
  id: randomUUID(),
  attempt: 1,
  event: 'bounced',
  messageId: randomUUID(),
  recipient: 'hardbounce@simulator.sendora.se',
  occurredAt: new Date().toISOString(),
  serverId: randomUUID(),
  streamId: randomUUID(),
  broadcastId: null,
  tag: 'contact-form',
  metadata: {},
  test: true,
  details: {
    code: 550,
    response: '5.1.1 No such user',
    classification: 'InvalidRecipient',
    hard: true,
    expired: false,
  },
});

// Signed as Sendora signs each delivery.
const secret = process.env.SENDORA_WEBHOOK_SECRET ?? '';
const t = String(Math.floor(Date.now() / 1000));
const v1 = createHmac('sha256', secret)
  .update(`${t}.${body}`)
  .digest('hex');

const response = await fetch(
  'http://localhost:3000/sendora/webhook',
  {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'sendora-signature': `t=${t},v1=${v1}`,
    },
    body,
  },
);
console.log(response.status);

Run it with node --env-file=.env scripts/try-webhook.ts. It prints 204 once the route has taken the delivery, and the app logs the bounce. The script and the route both read the secret from .env, so any value there works on your machine.