# Alert e-mails from a self-hosted engine

> Turn the alert webhook of your own engine into e-mail, with a small function on Amazon SES or a small server on any SMTP account.

Applies to: the Sypnia engine (open source, self-hosted). Status: at launch.  
Source: https://docs.sypnia.com/guides/alert-emails-self-hosted/

**\[Engine]** This guide is for whoever runs their own Sypnia engine and wants an e-mail when something breaks.

**The default deployment of the engine sends no e-mail.** It has no e-mail sender in it, on purpose: the engine stays small, and you choose the provider. What it does do is record every alert and post it to a webhook, if you set one. This guide puts a few lines of your own code on that webhook. On Sypnia Cloud you need none of this: alerts arrive by e-mail and in the app.

**At the end you will have:** an e-mail like this, within about two minutes of a new problem in production.

```text
Subject: [Shop] New problem: 1 person tried to pay and could not.

New problem: 1 person tried to pay and could not.

createPayment answered 400 in POST /api/checkout
1 person, 1 session, first seen 2026-03-12T09:12:04Z

Open it: https://sypnia.example.com/console/shop/problems/pay-button-does-nothing
```

**You need:** a running engine, an address you may send from, and either an AWS account (for SES) or an SMTP account from any provider.

## How it fits together

1. Something needs a person: a new problem, a problem that came back, your app not answering. The engine records an alert.
2. The engine posts the alert to your webhook, signed.
3. Your code checks the signature, writes the e-mail and hands it to SES or to your SMTP server.

The body of the post, with the fields this guide uses:

```json
{
  "id": "evt_7m3n9b5v1c8x",
  "type": "alert.created",
  "created_at": "2026-03-12T09:13:02Z",
  "project": { "id": "prj_5k2m9x4q7w1z", "slug": "shop", "name": "Shop" },
  "data": {
    "alert": {
      "id": "alt_6w2e8r4t1y9u",
      "kind": "problem.new",
      "title": "New problem: 1 person tried to pay and could not.",
      "environment": "production",
      "created_at": "2026-03-12T09:13:02Z",
      "url": "https://sypnia.example.com/console/shop/problems/pay-button-does-nothing"
    },
    "problem": {
      "slug": "pay-button-does-nothing",
      "title": "createPayment answered 400 in POST /api/checkout",
      "sentence": null,
      "people": 1,
      "sessions": 1,
      "first_seen": "2026-03-12T09:12:04Z"
    }
  }
}
```

`data.problem` is there when the alert is about a problem; `sentence` is `null` until the agent has analysed it, and stays `null` when no model key is set. Every field, the other event types, the signature and the retries are in [Alerts and webhooks](https://docs.sypnia.com/api/webhooks).

## The part both ways share

Save this file next to whichever sender you choose. It checks that a post really comes from your engine, and turns the event into an e-mail's subject and text.

`sypnia-alert.mjs`

```js
import { createHmac, timingSafeEqual } from 'node:crypto';

// True when the post was signed by your engine with the webhook secret, less than 5 minutes ago.
export function isFromSypnia(rawBody, header, secret) {
  const parts = Object.fromEntries(String(header).split(',').map((p) => p.split('=')));
  if (!parts.t || !parts.v1) return false;
  if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false;
  const expected = createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(parts.v1);
  return a.length === b.length && timingSafeEqual(a, b);
}

// The e-mail for one alert, as plain text.
export function emailFor(event) {
  const { alert, problem } = event.data;
  const lines = [alert.title, ''];
  if (problem) {
    lines.push(problem.sentence ?? problem.title);
    lines.push(`${problem.people} ${problem.people === 1 ? 'person' : 'people'}, ${problem.sessions} ${problem.sessions === 1 ? 'session' : 'sessions'}, first seen ${problem.first_seen}`);
    lines.push('');
  }
  lines.push(`Open it: ${alert.url}`);
  return { subject: `[${event.project.name}] ${alert.title}`, text: lines.join('\n') };
}
```

## Choose a sender

**Amazon SES**

A Lambda function with a Function URL receives the webhook and sends through SES.

### 1. Verify the sender in SES

In the Amazon SES console, verify the address or the domain you will send from, in the region you will use. A new SES account is in the sandbox and can only send to verified addresses; ask AWS for production access when you want to send to anyone.

**You should see:**The identity shows «Verified».

### 2. Create the function

Create a Lambda function on a current Node.js runtime, with a Function URL whose auth type is `NONE` (the signature is the check). Add `sypnia-alert.mjs` and this file:

`index.mjs`

```js
import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2';
import { isFromSypnia, emailFor } from './sypnia-alert.mjs';

const ses = new SESv2Client({});

export async function handler(request) {
  const raw = request.isBase64Encoded ? Buffer.from(request.body ?? '', 'base64').toString('utf8') : request.body ?? '';
  if (!isFromSypnia(raw, request.headers['sypnia-signature'], process.env.SYPNIA_WEBHOOK_SECRET)) {
    return { statusCode: 401, body: 'bad signature' };
  }

  const event = JSON.parse(raw);
  if (event.type !== 'alert.created') return { statusCode: 200, body: 'ignored' };

  const { subject, text } = emailFor(event);
  await ses.send(new SendEmailCommand({
    FromEmailAddress: process.env.ALERTS_FROM,
    Destination: { ToAddresses: process.env.ALERTS_TO.split(',') },
    Content: { Simple: { Subject: { Data: subject }, Body: { Text: { Data: text } } } },
  }));
  return { statusCode: 200, body: 'sent' };
}
```

Set three environment variables on the function:

`Function environment`

```bash
SYPNIA_WEBHOOK_SECRET=<a long random string; the same value goes to the engine in the next section>
ALERTS_FROM=alerts@shop.example
ALERTS_TO=you@shop.example,teammate@shop.example
```

Give the function's role one permission, limited to your sender:

`IAM policy`

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "ses:SendEmail",
    "Resource": "arn:aws:ses:us-east-1:123456789012:identity/shop.example"
  }]
}
```

**You should see:**The function has a URL like `https://abc123.lambda-url.us-east-1.on.aws/`. Opening it in a browser answers `bad signature`: that is correct.

**Any SMTP**

A small Node server receives the webhook and sends through your SMTP account. Run it anywhere your engine can reach: the same machine is fine.

### 1. Write the server

```bash
npm init -y && npm install nodemailer
```

`server.mjs`

```js
import { createServer } from 'node:http';
import nodemailer from 'nodemailer';
import { isFromSypnia, emailFor } from './sypnia-alert.mjs';

const mail = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT ?? 587),
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD },
});

createServer(async (req, res) => {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const raw = Buffer.concat(chunks).toString('utf8');

  if (req.method !== 'POST' || !isFromSypnia(raw, req.headers['sypnia-signature'], process.env.SYPNIA_WEBHOOK_SECRET)) {
    res.writeHead(401).end('bad signature');
    return;
  }
  const event = JSON.parse(raw);
  if (event.type === 'alert.created') {
    const { subject, text } = emailFor(event);
    await mail.sendMail({ from: process.env.ALERTS_FROM, to: process.env.ALERTS_TO, subject, text });
  }
  res.writeHead(200).end('ok');
}).listen(Number(process.env.PORT ?? 8787));
```

### 2. Run it

```bash
SYPNIA_WEBHOOK_SECRET=<a long random string> \
SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_USER=alerts@shop.example SMTP_PASSWORD=<password> \
ALERTS_FROM=alerts@shop.example ALERTS_TO=you@shop.example \
node server.mjs
```

**You should see:**The server listens on port 8787. `curl -i -X POST http://localhost:8787` answers `401 bad signature`: that is correct.

If the receiver is reached over plain `http` or on a private address, set `SYPNIA_WEBHOOKS_ALLOW_HTTP=true` on the engine. Keep it running with whatever keeps your other services running.

## Point the engine at it

Add two settings to the engine and restart it. The secret is the same string you gave your receiver.

`Engine environment`

```bash
SYPNIA_ALERT_WEBHOOK_URL=https://abc123.lambda-url.us-east-1.on.aws/
SYPNIA_ALERT_WEBHOOK_SECRET=<the same long random string>
```

This webhook receives the alerts of every project of the engine. To send one project's alerts somewhere else, register a webhook for that project through the [API](https://docs.sypnia.com/api/webhooks) instead; its secret is created for you and shown once.

## Check that it works

```bash
sypnia doctor --only webhook
```

**You should see:**`webhook   ok`, and your receiver answered `200`. The check sends a signed `ping`, which the code above accepts and does not turn into an e-mail.

Then cause a real alert. Alerts are created for the `production` environment only, so run your app once with `environment: 'production'` and throw a test error, as in [Your first problem](https://docs.sypnia.com/start/your-first-problem).

**You should see:**An e-mail within about 2 minutes. The same alert is in the Console and in `GET /v1/alerts`, whether or not the e-mail worked.

## What to know before you rely on it

- **Retries.** If your receiver does not answer `2xx`, the engine tries again later. A slow e-mail provider can therefore produce the same e-mail twice. Each event has an `id` that is the same on every retry: store the ids you have sent if duplicates matter to you.
- **No e-mail, no loss.** An alert that could not be delivered is still recorded, and you can read it in the Console, the API and the CLI.
- **Which alerts.** New problems, problems that came back or grow, uptime, slower pages, failing API routes and usage limits. The kinds and their thresholds are in [Alerts and the daily summary](https://docs.sypnia.com/concepts/alerts-and-daily-summary); you can switch each one off.
- **The daily summary** by e-mail is part of Sypnia Cloud. The engine does not produce it.
- **Keep the secret secret.** Anyone who has it can make your function send e-mail.
