SendForever help
Log in Get started

Help Monitoring

Webhook

A domain's webhook has Amazon SES in your own AWS account post what happens to every email the domain sends straight to a URL in your app. It also posts every change of subscription to the domain's audiences. This page covers which events you can choose, what each request contains, how to secure and test your endpoint, and how to change or remove it.

How it works

Amazon SES hands each email's events to the domain's Amazon SNS topic in your AWS account. The topic is named sendforever-webhook- followed by the domain with dashes, and it posts the events to your URL as they happen. The workflows in your account that change subscriptions send each change of subscription to the domain's audiences to the same topic. These reach your URL the same way, with the same retries. Nothing passes through SendForever, and there is no limit to how many events you receive.

Each domain has its own URL and its own choice of events. SendForever adds an event destination named sendforever-webhook to the domain's own configuration set. A domain you add starts without a webhook. If you move a domain to another team, set up its webhook again there.

The webhook is in the Webhook tab of the domain's Settings page. It needs a connected AWS account and the domain's own configuration set. Only team owners and admins can change it. Members can see it.

Set up the webhook

  1. Open the domain's Settings page and choose the Webhook tab.
  2. Under Set up the webhook, enter the Endpoint URL. It must be a full https:// address, since Amazon SNS only delivers over HTTPS. Put a secret token in it, for example https://app.example.com/webhooks/ses?token=....
  3. Under Events to post, choose the events you want. Bounces, complaints, deliveries and changes of subscription are chosen by default.
  4. Click Start posting events.

Amazon SNS then posts a SubscriptionConfirmation message to your endpoint. Your endpoint must fetch the SubscribeURL inside it, once. Until it does, the Your endpoint card shows Awaiting confirmation. Amazon SNS waits up to three days. While the page is open, it checks again every 30 seconds, and Check again checks right away. When the endpoint confirms, the badge says Confirmed and events start arriving.

If your code never saw the confirmation, look in your web server's or host's access log for a POST to the URL. A 419 or 403 there means CSRF protection or a wrong token rejected it. Fix that, then save again so the message is posted once more.

The events

Events to post lists every event Amazon SES publishes about your emails, plus changes of subscription, in four groups:

  • Delivery: Sent (Amazon SES accepted the email), Delivered (the recipient's mail server accepted it) and Delayed (the recipient's mail server could not accept it yet, and Amazon SES keeps trying).
  • Problems: Bounced (it could not be delivered), Complaint (the recipient marked it as spam), Rejected (Amazon SES found a virus in it and did not send it) and Rendering failure (a template could not be filled in with the data sent).
  • Engagement: Opened and Clicked.
  • Audiences: Subscription changed (someone unsubscribed from an audience, or subscribed to it again).

Choose at least one.

Opens and clicks are only posted while the domain tracks them. Tracking is what records them: it adds a pixel to every email and rewrites its links. When you choose Opened or Clicked, the form shows below them whether the domain tracks them. To turn tracking on, use Track opens and clicks on the domain's Configuration tab. Its opens and clicks are then posted too. See Domains.

Changes of subscription

A change of subscription is posted when someone leaves one of the domain's audiences or comes back to it. It does not matter what made the change: the unsubscribe link in an email, a mail provider's one-click unsubscribe, the preferences page, SendForever's pages, or your app through the subscriptions API. Joining an audience for the first time is not posted. When someone unsubscribes from everything the domain sends, one change is posted for each audience they were in.

Each one is JSON. It has type where Amazon SES's events have eventType, so one endpoint can tell them apart:

{
  "type": "unsubscribed",
  "email": "[email protected]",
  "audience": "weekly-news",
  "domain": "news.example.com",
  "configuration_set": "sendforever-news-example-com",
  "source": "email_link",
  "occurred_at": "2026-11-10T09:30:00.000Z"
}
  • type: unsubscribed (left the audience) or resubscribed (came back to it).
  • audience: the audience's name.
  • domain and configuration_set: the domain and its own configuration set. Amazon SES's events name the same configuration set in mail.tags["ses:configuration-set"].
  • source: what made the change: email_link (the unsubscribe link in an email, or the one your app put in its own), one_click (a mail provider's one-click unsubscribe), preferences_page, dashboard (SendForever's pages) or api (your app through the subscriptions API, including its imports). Your app's own changes are posted too, so ignore api if your app already knows about them.
  • occurred_at: when the change was made, in UTC.

What your endpoint receives

  1. The first request is a SubscriptionConfirmation. Fetch its SubscribeURL once, and the subscription is live.
  2. After that, each request carries one event as JSON: eventType (such as Bounce, Complaint or Delivery), mail, and a bounce, complaint, delivery or other object with the details. The body is the event exactly as Amazon SES publishes it. Amazon's documentation describes what each event contains.
  3. A change of subscription has type instead of eventType, as described in Changes of subscription.

The x-amz-sns-message-type header says whether a request is a SubscriptionConfirmation. The x-amz-sns-message-id header identifies the message.

What your endpoint should do

  • Check a secret token in the URL, since events come without a signature.
  • Answer with a 2xx status quickly.
  • Act once per x-amz-sns-message-id, since an event can arrive twice.

If the endpoint is down or answers with a 5xx or 429, Amazon SNS retries for close to an hour, at most a minute apart. Then it drops the event. Any other failure drops the event right away.

Example endpoint

The page shows ready-to-copy examples for Laravel, Node.js (Express), PHP (Symfony) and Python (Flask). All of them reject every request while no token is configured. They only fetch Amazon SNS's own confirmation link.

For Laravel, exempt the route from CSRF protection inside withMiddleware() in bootstrap/app.php:

// Amazon SNS sends no CSRF token. Before Laravel 13, call validateCsrfTokens() instead.
// If withMiddleware() already calls either, add 'webhooks/ses' to that call's except list:
// a second call would turn the first one's originOnly and allowSameSite back off.
$middleware->preventRequestForgery(except: ['webhooks/ses']);

Add the token to config/services.php, inside 'ses':

'webhook_token' => env('SES_WEBHOOK_TOKEN'), // A long random string, also put in the endpoint URL.

Then add the route to routes/web.php:

Route::post('/webhooks/ses', function (Request $request) {
    $token = config('services.ses.webhook_token');

    // Turns every request away while no token is configured.
    abort_unless(is_string($token) && $token !== '' && hash_equals($token, (string) $request->query('token')), 403);

    if ($request->header('x-amz-sns-message-type') === 'SubscriptionConfirmation') {
        $subscribeUrl = (string) $request->json('SubscribeURL');

        // Only Amazon SNS's own confirmation link is fetched.
        abort_unless(preg_match('#^https://sns\.[a-z0-9-]+\.amazonaws\.com/#', $subscribeUrl) === 1, 403);

        Http::get($subscribeUrl); // Confirms the subscription, once.

        return response()->noContent();
    }

    $event = $request->json()->all(); // eventType, mail, bounce... or type, for a change of subscription

    match ($event['eventType'] ?? $event['type'] ?? null) {
        'Bounce' => BounceReceived::dispatch($event['bounce']['bouncedRecipients'], $event['mail']),
        'Complaint' => ComplaintReceived::dispatch($event['complaint']['complainedRecipients'], $event['mail']),
        'unsubscribed', 'resubscribed' => SubscriptionChanged::dispatch($event), // email, audience, source...
        default => null,
    };

    return response()->noContent();
});

For Node.js with Express:

import { timingSafeEqual } from 'node:crypto';

app.post('/webhooks/ses', express.text({ type: '*/*' }), async (req, res) => {
  const expected = Buffer.from(process.env.SES_WEBHOOK_TOKEN ?? '');
  const given = Buffer.from(String(req.query.token ?? ''));

  // Turns every request away while no token is configured.
  if (expected.length === 0 || given.length !== expected.length || !timingSafeEqual(given, expected)) {
    return res.sendStatus(403);
  }

  const body = JSON.parse(req.body);

  if (req.get('x-amz-sns-message-type') === 'SubscriptionConfirmation') {
    // Only Amazon SNS's own confirmation link is fetched.
    if (!/^https:\/\/sns\.[a-z0-9-]+\.amazonaws\.com\//.test(body.SubscribeURL)) return res.sendStatus(403);

    await fetch(body.SubscribeURL); // Confirms the subscription, once.
    return res.sendStatus(204);
  }

  switch (body.eventType ?? body.type) { // 'Bounce', 'Complaint', 'Delivery'... or a change of subscription
    case 'Bounce':
      await markBounced(body.bounce.bouncedRecipients, body.mail);
      break;
    case 'Complaint':
      await markComplained(body.complaint.complainedRecipients, body.mail);
      break;
    case 'unsubscribed':
    case 'resubscribed':
      await changeSubscription(body); // email, audience, source...
      break;
  }

  res.sendStatus(204);
});

For PHP with Symfony, a controller in src/Controller/SesWebhookController.php:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class SesWebhookController extends AbstractController
{
    #[Route('/webhooks/ses', methods: ['POST'])]
    public function __invoke(
        Request $request,
        HttpClientInterface $http,
        MessageBusInterface $bus,
        #[Autowire(env: 'SES_WEBHOOK_TOKEN')] string $token, // A long random string, also put in the endpoint URL.
    ): Response {
        // Turns every request away while no token is configured.
        if ($token === '' || ! hash_equals($token, $request->query->getString('token'))) {
            return new Response(status: 403);
        }

        if ($request->headers->get('x-amz-sns-message-type') === 'SubscriptionConfirmation') {
            $subscribeUrl = (string) ($request->toArray()['SubscribeURL'] ?? '');

            // Only Amazon SNS's own confirmation link is fetched.
            if (preg_match('#^https://sns\.[a-z0-9-]+\.amazonaws\.com/#', $subscribeUrl) !== 1) {
                return new Response(status: 403);
            }

            $http->request('GET', $subscribeUrl); // Confirms the subscription, once.

            return new Response(status: 204);
        }

        $event = $request->toArray(); // eventType, mail, bounce... or type, for a change of subscription

        match ($event['eventType'] ?? $event['type'] ?? null) {
            'Bounce' => $bus->dispatch(new BounceReceived($event['bounce']['bouncedRecipients'], $event['mail'])),
            'Complaint' => $bus->dispatch(new ComplaintReceived($event['complaint']['complainedRecipients'], $event['mail'])),
            'unsubscribed', 'resubscribed' => $bus->dispatch(new SubscriptionChanged($event)), // email, audience, source...
            default => null,
        };

        return new Response(status: 204);
    }
}

For Python with Flask:

import hmac, os, re
from urllib.request import urlopen
from flask import abort, request

@app.post("/webhooks/ses")
def ses_webhook():
    expected = os.environ.get("SES_WEBHOOK_TOKEN", "").encode()
    given = request.args.get("token", "").encode()

    # Turns every request away while no token is configured.
    if not expected or not hmac.compare_digest(given, expected):
        abort(403)

    body = request.get_json(force=True)  # Amazon SNS posts its JSON as text/plain.

    if request.headers.get("x-amz-sns-message-type") == "SubscriptionConfirmation":
        # Only Amazon SNS's own confirmation link is fetched.
        if not re.match(r"https://sns\.[a-z0-9-]+\.amazonaws\.com/", body.get("SubscribeURL", "")):
            abort(403)

        urlopen(body["SubscribeURL"]).close()  # Confirms the subscription, once.
        return "", 204

    match body.get("eventType") or body.get("type"):  # Bounce, Complaint, Delivery... or a change of subscription
        case "Bounce":
            mark_bounced(body["bounce"]["bouncedRecipients"], body["mail"])
        case "Complaint":
            mark_complained(body["complaint"]["complainedRecipients"], body["mail"])
        case "unsubscribed" | "resubscribed":
            change_subscription(body)  # email, audience, source...

    return "", 204

Test the webhook

No button posts a sample event. To see real events arrive, send yourself a test email from the domain with Send me a test email in the actions menu of the domain's Settings page. The test email goes through the domain's configuration set, so its events are posted like any other email's. See Sending email from your app. To see a change of subscription, add yourself to one of the domain's audiences, then unsubscribe from it on the audience page.

Change the events or the URL

Change the URL or the events under Change the webhook and click Save.

  • If you save the same URL with other events, what is posted changes. Your endpoint does not have to confirm again.
  • If you save a new URL while an endpoint is confirmed, the page asks first, in Switch the webhook to the new URL?. The current endpoint stops receiving events as soon as you switch, before the new one confirms. Events sent in between reach neither endpoint. Have the new endpoint ready to fetch the SubscribeURL, then click Switch URL.

Remove the webhook

Click Remove webhook and confirm. Your endpoint stops receiving events right away. The event destination is removed, and the domain's topic in your AWS account is deleted along with its subscription. Nothing else changes. Removing the domain also removes its webhook.

Notices on the page

  • Emails sent through sendforever-example-com are not posted yet. Save to add it.: the domain's configuration set is not posting to the webhook. Click Save.
  • Amazon SNS retries this endpoint for only about a minute, then drops the event.: the webhook was set up before retries were spread over close to an hour. Click Save.
  • Give this domain its own configuration set first: the domain shares a configuration set or has none. Click Apply recommended settings on its Configuration tab.
  • Unable to reach your AWS account: the page could not read the webhook. A webhook that is already set up keeps posting events. Click Try again.

Common questions

Why are no events arriving?

Check that Your endpoint says Confirmed. If it says Awaiting confirmation, your endpoint has not fetched the SubscribeURL yet. Look for the POST in your access log, then save again so the confirmation is posted once more.

How do I verify that a request comes from my AWS account?

The events come without a signature. Put a long random token in the endpoint URL and check it on every request, as the examples do.

Why do I get the same event twice?

Amazon SNS may deliver a message more than once. Act once per x-amz-sns-message-id.

Why are opens and clicks not posted?

Only domains that track opens and clicks post them. Turn on Track opens and clicks on the domain's Configuration tab.

Can I have a different URL per domain?

Yes, each domain has its own. To receive several domains on one URL, set that URL up on each domain. Your endpoint confirms each one once. The mail object of each event says which domain sent the email, and each change of subscription names its domain and configuration_set.

What happens when my endpoint is down?

If the endpoint is down or answers with a 5xx or 429, Amazon SNS retries for close to an hour, then drops the event. Any other failure drops it right away. The activity log still has every email's events.

Does the webhook cost anything?

It runs through Amazon SNS in your AWS account. The activity log, the webhook, alerts and campaigns add cents at most to your AWS bill. Most of that falls within AWS's free tier.

Who can change the webhook?

Team owners and admins. Members see Only team owners and admins can change the webhook.

Still stuck?

, which answers from these pages.

No page or section has those words.

Ask AI

ChatGPT or Claude answers in a new tab, from the SendForever docs. Only your question goes with it, nothing about your team.

Or read the help center

ChatGPT Claude