Webhooks
The events Mailset posts about your product’s email, and how to check a request’s signature.
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
- Pick an https URL on port 443 under a public host name, such as
https://hooks.example.com/mailset. - Run
mailset hooks set --url https://hooks.example.com/mailset. It prints the signing secret once: keep it asMAILSET_HOOK_SECRET. - Run
mailset hooks testto post one signedtestevent 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 commands.
The request
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":"moc.elpmaxe@85a4d2b7e0c1a9f3","recipient":"gro.elpmaxe@ana","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.
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 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 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 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.
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;
}
}
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
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 {
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
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);
}
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 {
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 {
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.
- Read the body as raw bytes, before any JSON parsing.
- Compute HMAC-SHA256 over
<t>.<body>with the secret, as lowercase hex. - Compare it with
v1in constant time. - Refuse a timestamp more than 5 minutes from your clock, so a captured request can't be replayed.
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.
// 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"`
}
# 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
// 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;
/**
* 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);
// 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()
}
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:
{"events":[{"id":"mev_3f9a1c2e7b","type":"delivered","at":1799999990000,"message":"out_8d2k4m","messageId":"elpmaxe.emca@f3e5d6b7a9c0f1e4","recipient":"moc.elpmaxe@ana","app":"Café Luna"},{"id":"mev_a71c05d9e4","type":"bounced","at":1799999995000,"message":"out_8d2k4n","messageId":"elpmaxe.emca@b1a2f3e4d5c6a7b9","recipient":"gro.elpmaxe@ydobon","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:
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-Deliveryand 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 getshows where events go, how many wait, and why the last batch didn't go.mailset hooks rotatemakes a new secret and the old one stops at once.
Campaigns have a hook of their own, set with mailset campaigns hook set.