# Webhooks

Mailset posts what became of each message your product sent to one URL on your server. One event per recipient, in signed batches of up to 100.

Only email sent with an app key has events. A person's own email has notices in their mailbox instead.

## Set it up

1. Pick an https URL on port 443 under a public host name, such as `https://hooks.example.com/mailset`.
2. Run `mailset hooks set --url https://hooks.example.com/mailset`. It prints the signing secret once: keep it as `MAILSET_HOOK_SECRET`.
3. Run `mailset hooks test` to post one signed `test` event now and see what your server answered.

An owner or admin of the org sets the hook, in the CLI, in the app under Settings, Developers, or with the [Event hook](https://mailset.app/docs/api/hooks) commands.

## The request

```http
POST /mailset
Content-Type: application/json
Mailset-Signature: t=1800000000,v1=8d3efce7…
Mailset-Delivery: <batch id>

{"events":[{"id":"mev_3f9a1c2e7b","type":"delivered","at":1799999990000,"message":"out_8d2k4m","messageId":"3f9a1c0e7b2d4a58@example.com","recipient":"ana@example.org","app":"Acme API"}]}
```

Answer any 2xx once you have kept the events. Mailset reads only the status.

## Events

| Type | What happened |
| --- | --- |
| `queued` | A limit holds the message. `sendsAt` says when it should go and `reason` says why. |
| `sent` | Mailset handed the message on for delivery. |
| `delivered` | The recipient’s server took it. |
| `bounced` | It came back. `bounce.kind` is `hard` or `soft`, and `bounce.class` says what that means for the address. |
| `complained` | The recipient marked it as spam. Stop writing to them. |
| `failed` | Mailset couldn’t send it: it was refused, its key was paused, or five tries failed. `reason` says which. |
| `expired` | Its `deliverBy` came while it waited, so it never went. |
| `unsubscribed` | The recipient opted out of this sender’s promotional email through Mailset’s unsubscribe link. |
| `test` | Sent by `mailset hooks test`. About no message. |

Every field an event can carry is in [The Event object](https://mailset.app/docs/api/hooks#event).

Every event about a message carries these fields:

| Field         | What it is                                                      |
| ------------- | --------------------------------------------------------------- |
| `id`          | Stable for this message, recipient and happening. Dedupe on it. |
| `type`        | One of the types above. Ignore a type you don't know yet.       |
| `at`          | When it happened, in milliseconds since the epoch.              |
| `message`     | Mailset's id for the message: the `id` its send answered.       |
| `messageId`   | Its Message-ID header, without the angle brackets.              |
| `recipient`   | One address. A message to three people has three of each event. |
| `app`         | The key that sent it, by the name it was approved with.         |
| `duplicateOf` | Only on a repeat: the `message` of the earlier send it repeats. |

An event never carries a subject or anything from the body.

`duplicateOf` is there when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID. Both were sent. [Retry without sending twice](https://mailset.app/docs/recipes/retries) says how to stop it.

`bounced` adds `bounce`, with `kind` (`hard` or `soft`), `class` and `reason`. The classes are `mailbox` and `domain` (the address can't get email), `full`, `too_large`, `policy`, `suppressed` and `other`. [Handle bounces](https://mailset.app/docs/recipes/bounces) says what to do with each.

`reason` is the receiving server's reply with its SMTP code, such as `smtp; 550 5.1.1 The email account that you tried to reach does not exist.` A `suppressed` bounce never reached a server, so its `reason` is in Mailset's words: the address bounced hard or complained before. When Mailset refuses a message itself, as when a virus scan flags it, the `failed` event's `reason` says so in Mailset's words too. Show `reason` to people, and match on `class` in code.

`unsubscribed` is about a person and a sender more than one message: it carries `recipient`, and `message`, `messageId` and `app` when the link's message is known. [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes) covers it.

## Check the signature

Every request is signed with the hook's secret. The SDK's `webhooks.verify` checks the signature and the request's age, then hands you the events. It needs no `MAILSET_KEY`, so a service that only receives events imports `webhooks` alone.

```typescript
import { MailsetError, webhooks } from 'mailset';

export async function POST(request: Request) {
	try {
		const events = await webhooks.verify({
			body: await request.text(),
			headers: request.headers,
			secret: process.env.MAILSET_HOOK_SECRET ?? '',
		});
		for (const event of events) {
			if (event.type !== 'bounced') continue;
			if (event.bounce.kind === 'hard')
				console.log('Stop writing to', event.recipient);
		}
		// 2xx once the events are kept.
		// Until then Mailset posts the batch again.
		return new Response(null, { status: 204 });
	} catch (error) {
		if (error instanceof MailsetError)
			return new Response(error.code, { status: 401 });
		throw error;
	}
}
```

```python
import os
from typing import Mapping

from mailset import MailsetError, webhooks

SECRET = os.environ["MAILSET_HOOK_SECRET"]


def handle(
    body: bytes, headers: Mapping[str, str]
) -> int:
    """Your hook's endpoint: the body as it came,
    and its headers. Answers the HTTP status."""
    try:
        events = webhooks.verify(body, headers, SECRET)
    except MailsetError as error:
        print(error.code)
        return 401
    for event in events:
        if event["type"] != "bounced":
            continue
        if event["bounce"]["kind"] == "hard":
            print("Stop writing to", event["recipient"])
    # 2xx once the events are kept.
    # Until then Mailset posts the batch again.
    return 204
```

```go
import (
	"fmt"
	"io"
	"log"
	"os"

	mailset "mailset.app/go"
)

// handle checks one request from your org's hook:
// its body as it came, and its Mailset-Signature.
// It needs no client and no key.
func handle(body []byte, signature string) error {
	secret := os.Getenv("MAILSET_HOOK_SECRET")
	events, err := mailset.VerifyWebhook(
		body, signature, secret,
	)
	if err != nil {
		// unauthorized, expired or invalid_input:
		// answer 401.
		return err
	}
	for _, event := range events {
		switch event.Type {
		case mailset.EventBounced:
			if event.Bounce.Kind == mailset.BounceHard {
				fmt.Println("Stop writing to", event.Recipient)
			}
		case mailset.EventComplained,
			mailset.EventUnsubscribed:
			fmt.Println("Take", event.Recipient, "off the list")
		}
	}
	// Answer 2xx once the events are kept.
	// Until then Mailset posts the batch again.
	return nil
}
```

```ruby
require 'mailset'

# A Rack app Mailset posts your hook's events to.
MAILSET_EVENTS = lambda do |env|
  events = Mailset::Webhooks.verify(
    body: env['rack.input'].read,
    headers: env,
    secret: ENV.fetch('MAILSET_HOOK_SECRET')
  )
  events.each do |event|
    next unless event.type == 'bounced'
    next unless event.bounce.hard?

    puts "Stop writing to #{event.recipient}"
  end
  # 2xx once the events are kept.
  # Until then Mailset posts the batch again.
  [204, {}, []]
rescue Mailset::Error => e
  [401, {}, [e.code]]
end
```

```php
<?php

require 'vendor/autoload.php';

use Mailset\Events\BouncedEvent;
use Mailset\MailsetException;
use Mailset\Webhooks;

try {
    $events = Webhooks::verify(
        (string) file_get_contents('php://input'),
        getallheaders(),
        (string) getenv('MAILSET_HOOK_SECRET'),
    );
} catch (MailsetException $error) {
    http_response_code(401);
    exit($error->errorCode);
}
foreach ($events as $event) {
    if (!$event instanceof BouncedEvent) {
        continue;
    }
    if ($event->bounce->kind === 'hard') {
        error_log("Stop writing to {$event->recipient}");
    }
}
// 2xx once the events are kept.
// Until then Mailset posts the batch again.
http_response_code(204);
```

```java
import app.mailset.MailEvent;
import app.mailset.MailsetException;
import app.mailset.Webhooks;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.util.List;

// POST /mailset/events, on the JDK's own server.
static void events(HttpExchange exchange)
        throws IOException {
    // The signature covers the body exactly as it
    // came: read its bytes.
    byte[] body =
            exchange.getRequestBody().readAllBytes();
    String signature = exchange.getRequestHeaders()
            .getFirst("Mailset-Signature");
    int status = 204;
    try {
        List<MailEvent> events =
                Webhooks.verify(body, signature, secret);
        for (MailEvent event : events) {
            if (event instanceof MailEvent.Bounced b
                    && b.bounce().kind().equals("hard"))
                stopWritingTo(b.recipient());
        }
        // 2xx once the events are kept. Until then
        // Mailset posts the batch again.
    } catch (MailsetException error) {
        status = 401;
    }
    exchange.sendResponseHeaders(status, -1);
    exchange.close();
}
```

```rust
use mailset::webhooks::{self, Event};

/// Your hook's route, in any framework: the raw body
/// as it came, and the `Mailset-Signature` header.
/// Answers the status to reply with.
pub fn handle(
    body: &[u8],
    signature: Option<&str>,
) -> u16 {
    let secret = std::env::var("MAILSET_HOOK_SECRET");
    let secret = secret.unwrap_or_default();
    let verified =
        webhooks::verify(body, signature, &secret);
    let Ok(events) = verified else {
        return 401;
    };
    for event in events {
        let Event::Bounced(bounced) = event else {
            continue;
        };
        if bounced.bounce.is_hard() {
            let to = &bounced.recipient;
            println!("Stop writing to {to}");
        }
    }
    // 2xx once the events are kept.
    // Until then Mailset posts the batch again.
    204
}
```

Give it the body as it arrived, before any JSON parsing. A request that fails the check throws a `MailsetError`: answer it `401`.

## Without an SDK

`Mailset-Signature` is `t=<unix seconds>,v1=<hex>`. The hex is HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the hook's secret.

1. Read the body as raw bytes, before any JSON parsing.
2. Compute HMAC-SHA256 over `<t>.<body>` with the secret, as lowercase hex.
3. Compare it with `v1` in constant time.
4. Refuse a timestamp more than 5 minutes from your clock, so a captured request can't be replayed.

```python
def verify(
    body: bytes, signature_header: str, secret: str, now_seconds=None, tolerance=300
) -> list:
    """The events in a webhook, once its Mailset-Signature header checks out.

    body is the raw request body, before any JSON parsing: the signature
    covers those bytes. Raises ValueError for anything Mailset didn't send.
    """
    # Mailset-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
    header = (signature_header or "").strip()
    signed = re.fullmatch(r"t=([0-9]+),v1=([0-9a-f]{64})", header)
    if not signed:
        raise ValueError("This request carries no Mailset-Signature.")
    timestamp, theirs = signed.groups()

    signed_bytes = timestamp.encode() + b"." + body
    ours = hmac.new(secret.encode(), signed_bytes, hashlib.sha256).hexdigest()
    # compare_digest takes the same time wherever the two differ.
    if not hmac.compare_digest(ours, theirs):
        raise ValueError(
            "The Mailset-Signature doesn't match. Check the hook's secret."
        )

    # A captured request can't be replayed later than this.
    now = time.time() if now_seconds is None else now_seconds
    if abs(now - int(timestamp)) > tolerance:
        raise ValueError("The Mailset-Signature is too old.")

    batch = json.loads(body)
    if not isinstance(batch, dict) or not isinstance(batch.get("events"), list):
        raise ValueError("That body isn't a batch of Mailset events.")
    return batch["events"]
```

```go
// Event is one thing that happened to one recipient's copy of a message.
type Event struct {
	ID        string `json:"id"`
	Type      string `json:"type"` // queued, sent, delivered, bounced, complained, failed, expired, test
	At        int64  `json:"at"`   // ms since the epoch
	Message   string `json:"message"`
	MessageID string `json:"messageId"`
	Recipient string `json:"recipient"`
	App       string `json:"app"`
	SendsAt   int64  `json:"sendsAt"`
	Reason    string `json:"reason"`
	Bounce    *struct {
		Kind   string `json:"kind"` // hard or soft
		Class  string `json:"class"`
		Reason string `json:"reason"`
	} `json:"bounce"`
}

// Mailset-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
var signature = regexp.MustCompile(`^t=([0-9]+),v1=([0-9a-f]{64})$`)

// verify returns the events in a webhook, once its Mailset-Signature header
// checks out. body is the raw request body, before any JSON parsing: the
// signature covers those bytes.
func verify(
	body []byte, signatureHeader, secret string, now time.Time, tolerance time.Duration,
) ([]Event, error) {
	signed := signature.FindStringSubmatch(strings.TrimSpace(signatureHeader))
	if signed == nil {
		return nil, errors.New("this request carries no Mailset-Signature")
	}
	timestamp, theirs := signed[1], signed[2]

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(timestamp + "."))
	mac.Write(body)
	ours := hex.EncodeToString(mac.Sum(nil))
	// hmac.Equal takes the same time wherever the two differ.
	if !hmac.Equal([]byte(ours), []byte(theirs)) {
		return nil, errors.New("the Mailset-Signature doesn't match: check the hook's secret")
	}

	// A captured request can't be replayed later than this.
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil || now.Sub(time.Unix(seconds, 0)).Abs() > tolerance {
		return nil, errors.New("the Mailset-Signature is too old")
	}

	var batch struct {
		Events []Event `json:"events"`
	}
	if err := json.Unmarshal(body, &batch); err != nil || batch.Events == nil {
		return nil, errors.New("that body isn't a batch of Mailset events")
	}
	return batch.Events, nil
}
```

```ruby
# The events in a webhook, once its Mailset-Signature header checks out.
# body is the raw request body, before any JSON parsing: the signature covers
# those bytes. Raises ArgumentError for anything Mailset didn't send.
def verify(body, signature_header, secret, now_seconds: Time.now.to_i, tolerance: 300)
  # Mailset-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
  signed = /\At=([0-9]+),v1=([0-9a-f]{64})\z/.match(signature_header.to_s.strip)
  raise ArgumentError, 'This request carries no Mailset-Signature.' unless signed

  timestamp, theirs = signed.captures
  ours = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.#{body}")
  # secure_compare takes the same time wherever the two differ.
  unless OpenSSL.secure_compare(ours, theirs)
    raise ArgumentError, "The Mailset-Signature doesn't match. Check the hook's secret."
  end

  # A captured request can't be replayed later than this.
  if (now_seconds - timestamp.to_i).abs > tolerance
    raise ArgumentError, 'The Mailset-Signature is too old.'
  end

  batch = JSON.parse(body)
  unless batch.is_a?(Hash) && batch['events'].is_a?(Array)
    raise ArgumentError, "That body isn't a batch of Mailset events."
  end

  batch['events']
end
```

```php
// The events in a webhook, once its Mailset-Signature header checks out.
// $body is the raw request body, before any JSON parsing: the signature covers
// those bytes. In a web request that is file_get_contents('php://input').
// Throws UnexpectedValueException for anything Mailset didn't send.
function verify(
    string $body,
    ?string $signatureHeader,
    string $secret,
    ?int $nowSeconds = null,
    int $tolerance = 300,
): array {
    // Mailset-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
    if (!preg_match('/^t=([0-9]+),v1=([0-9a-f]{64})$/D', trim($signatureHeader ?? ''), $signed)) {
        throw new UnexpectedValueException('This request carries no Mailset-Signature.');
    }
    [, $timestamp, $theirs] = $signed;

    $ours = hash_hmac('sha256', $timestamp . '.' . $body, $secret);
    // hash_equals takes the same time wherever the two differ.
    if (!hash_equals($ours, $theirs)) {
        throw new UnexpectedValueException("The Mailset-Signature doesn't match. Check the hook's secret.");
    }

    // A captured request can't be replayed later than this.
    if (abs(($nowSeconds ?? time()) - (int) $timestamp) > $tolerance) {
        throw new UnexpectedValueException('The Mailset-Signature is too old.');
    }

    $batch = json_decode($body, true);
    if (!is_array($batch) || !is_array($batch['events'] ?? null)) {
        throw new UnexpectedValueException("That body isn't a batch of Mailset events.");
    }
    return $batch['events'];
}
```

```java
/**
 * Mailset-Signature: t=(unix seconds),v1=(hex HMAC-SHA256 of "t.body").
 * At most 18 digits, so the time always fits a long.
 */
static final Pattern SIGNATURE = Pattern.compile("t=([0-9]{1,18}),v1=([0-9a-f]{64})");

/**
 * The webhook's JSON, {"events":[...]}, once its Mailset-Signature header
 * checks out. The JDK has no JSON parser, so hand the text to yours.
 * body is the raw request body, before any parsing: the signature covers
 * those bytes. Throws SignatureException for anything Mailset didn't send.
 */
static String verify(
        byte[] body, String signatureHeader, String secret, long nowSeconds, long tolerance)
        throws GeneralSecurityException {
    Matcher signed = SIGNATURE.matcher(signatureHeader == null ? "" : signatureHeader.strip());
    if (!signed.matches()) {
        throw new SignatureException("This request carries no Mailset-Signature.");
    }
    String timestamp = signed.group(1);
    String theirs = signed.group(2);

    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
    byte[] ours = mac.doFinal(body);
    // MessageDigest.isEqual takes the same time wherever the two differ.
    if (!MessageDigest.isEqual(ours, HexFormat.of().parseHex(theirs))) {
        throw new SignatureException(
                "The Mailset-Signature doesn't match. Check the hook's secret.");
    }

    // A captured request can't be replayed later than this.
    if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > tolerance) {
        throw new SignatureException("The Mailset-Signature is too old.");
    }
    return new String(body, StandardCharsets.UTF_8);
}
```

```rust
// Crates: hmac 0.13, serde_json 1 and sha2 0.11.
use hmac::{Hmac, KeyInit, Mac};
use serde_json::Value;
use sha2::Sha256;

/// 64 lowercase hex characters as 32 bytes.
fn unhex(text: &str) -> Option<Vec<u8>> {
    if text.len() != 64
        || !text
            .bytes()
            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
    {
        return None;
    }
    (0..64)
        .step_by(2)
        .map(|at| u8::from_str_radix(&text[at..at + 2], 16).ok())
        .collect()
}

/// The events in a webhook, once its Mailset-Signature header checks out.
/// body is the raw request body, before any JSON parsing: the signature
/// covers those bytes. An error says why this isn't from Mailset.
fn verify(
    body: &[u8],
    signature_header: &str,
    secret: &str,
    now_seconds: u64,
    tolerance: u64,
) -> Result<Vec<Value>, Box<dyn Error>> {
    // Mailset-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
    let missing = "This request carries no Mailset-Signature.";
    let (timestamp, theirs) = signature_header
        .trim()
        .strip_prefix("t=")
        .and_then(|rest| rest.split_once(",v1="))
        .ok_or(missing)?;
    let theirs = unhex(theirs).ok_or(missing)?;
    if timestamp.is_empty() || !timestamp.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(missing.into());
    }

    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())?;
    mac.update(timestamp.as_bytes());
    mac.update(b".");
    mac.update(body);
    // verify_slice takes the same time wherever the two differ.
    mac.verify_slice(&theirs)
        .map_err(|_| "The Mailset-Signature doesn't match. Check the hook's secret.")?;

    // A captured request can't be replayed later than this. A timestamp too
    // long for a u64 is no time at all.
    let old = "The Mailset-Signature is too old.";
    if now_seconds.abs_diff(timestamp.parse().map_err(|_| old)?) > tolerance {
        return Err(old.into());
    }

    let batch: Value = serde_json::from_slice(body).unwrap_or_default();
    match batch["events"].as_array() {
        Some(events) => Ok(events.clone()),
        None => Err("That body isn't a batch of Mailset events.".into()),
    }
}
```

### Test vector

The secret here is a public example, made for this page.

The hook’s secret is `mhs_example-hook-secret-not-a-real-one`, and the request arrived with timestamp `1800000000` and this body:

```json
{"events":[{"id":"mev_3f9a1c2e7b","type":"delivered","at":1799999990000,"message":"out_8d2k4m","messageId":"4e1f0c9a7b6d5e3f@acme.example","recipient":"ana@example.com","app":"Café Luna"},{"id":"mev_a71c05d9e4","type":"bounced","at":1799999995000,"message":"out_8d2k4n","messageId":"9b7a6c5d4e3f2a1b@acme.example","recipient":"nobody@example.org","app":"Café Luna","bounce":{"kind":"hard","class":"mailbox","reason":"550 5.1.1 The email account that you tried to reach does not exist"}}]}
```

The header it must carry, exactly:

```http
Mailset-Signature: t=1800000000,v1=8d3efce713d0359ff51e7972095d32791bba89bfbed83567acd7d5722072ea62
```

HMAC gives the same answer every time, so your code must produce this header exactly. The body has a non-ASCII letter in it on purpose: hash the bytes as they arrived, never text you decoded and encoded again.

## Retries

- A batch your server doesn't answer 2xx is posted again, with the same `Mailset-Delivery` and the same event ids, for three days. Then Mailset drops it and tells whoever set the hook.
- Dedupe on `id`. The same happening always has the same id, even when it is reported twice.
- A redirect counts as not taken: Mailset doesn't follow it. Set the new URL when a hook moves.
- A post gives up after 15 seconds. Keep the events and answer, then do the slow work.
- `mailset hooks get` shows where events go, how many wait, and why the last batch didn't go.
- `mailset hooks rotate` makes a new secret and the old one stops at once.

Campaigns have a hook of their own, set with `mailset campaigns hook set`.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content