Bouncewise

Bouncewise › Guides › Mailgun webhooks: events, payload, signing and retries

Mailgun guide

Mailgun webhooks: events, payload, signing and retries

By the Bouncewise team · Updated · 3 min read · How we check guides

Short answer

Mailgun webhooks POST a JSON body to your URL for eight event types: accepted, delivered, temporary_fail, permanent_fail, opened, clicked, unsubscribed and complained. Each body has a signature object (timestamp, token, signature) and the event-data; verify it by computing HMAC-SHA256 of timestamp + token with your account's HTTP webhook signing key, not your API key. Return 200 to acknowledge, 406 to refuse without retries; any other answer is retried for up to 8 hours.

Event types and where to set them

WebhookFires whenSame as the Logs event
acceptedMailgun queued the messageaccepted
deliveredThe recipient's server accepted itdelivered
temporary_failDeferred or DNS didn't resolve; Mailgun will retryfailed with severity: temporary
permanent_failHard bounce, suppressed address, retries exhausted; no more attemptsfailed with severity: permanent
opened, clickedTracking is on and the tracking CNAME points to Mailgunsame names
unsubscribedRecipient used Mailgun's unsubscribe linkunsubscribed
complainedA feedback loop reported a spam complaintcomplained

There is no webhook for rejected. Inbound mail reaches you through a Route's forward() or store(notify=…) action instead, signed the same way.

Set them up under Send › Sending › Webhooks, at domain level (one domain) or account level (every domain and subaccount). Each event type takes up to 3 URLs. The same URL at both levels gets the event once. US and EU are separate: create webhooks in each region you send from. An HTTPS URL needs a certificate signed by a trusted CA; self-signed certificates don't work.

What the payload looks like

Every POST is application/json with two keys. A permanent failure, shortened from Mailgun's examples:

{
  "signature": {
    "token": "e0b5477167110d68991efc6b9f89f0a11066af27834600e123",
    "timestamp": "1770920772",
    "signature": "12d99f5a15355c180971bed7494d578b093c958f57766f3fe750761baed12345"
  },
  "event-data": {
    "event": "failed",
    "severity": "permanent",
    "reason": "bounce",
    "id": "…",
    "timestamp": 1770920775.12,
    "recipient": "[email protected]",
    "domain": {"name": "mg.example.com"},
    "message": {"headers": {"message-id": "[email protected]"}},
    "delivery-status": {
      "code": 550,
      "enhanced-code": "5.5.0",
      "message": "5.5.0 Requested action not taken: mailbox unavailable …",
      "bounce-type": "hard"
    },
    "tags": ["password-reset"],
    "user-variables": []
  }
}

The payload's event is the Logs name (failed), not the webhook name (permanent_fail), so branch on event plus severity. Match events to your own records with message.headers.message-id or the v: variables you sent, which come back in user-variables. Mailgun adds fields over time and says not to hard-code the list. With PII redaction switched on, recipient and IP fields arrive as [REDACTED], but the message ID stays.

Verify the signature

Mailgun signs every webhook with the account's HTTP webhook signing key, found under Settings › API Security. It is one key for every domain, and it is neither your API key nor a domain sending key. Using the API key is the most common reason every signature fails.

  1. Concatenate timestamp and token with no separator.
  2. Compute HMAC-SHA256 of that string, keyed with the signing key, as a hex digest.
  3. Compare it with signature; reject the request if they differ.
  4. Optionally keep used tokens and refuse repeats (replays), and refuse timestamps far from now, with some tolerance for delays.
import hmac, hashlib

def is_from_mailgun(signing_key: str, sig: dict) -> bool:
    expected = hmac.new(
        signing_key.encode(),
        (sig["timestamp"] + sig["token"]).encode(),
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, sig["signature"])

For subaccount domains the object also has parent-signature, computed with the primary account's key, so one key can check every subaccount. As an extra check, Mailgun presents a TLS client certificate issued by DigiCert with the Common Name webhooks.mgsend.net.

Retries, and what your endpoint should return

Your responseMailgun does
200Success; no retry.
406 Not AcceptableTreats the POST as rejected; no retry.
Anything else, including other 2xx and 4xxRetries, except for delivery notifications.

Mailgun's documentation gives the retry intervals as 5 minutes, 10 minutes, 15 minutes, 1 hour, 2 hours and 4 hours, over 8 hours; its help centre lists a slightly different sequence that also ends at 4 hours. Either way, plan for up to 8 hours of retries and don't depend on exact timing. Failed attempts, with the URL and reason, are listed on the Failure logs tab of the Webhooks page.

Because retries and slow responses can deliver the same event twice, answer 200 as soon as the event is stored, process it in the background, and ignore repeats. The event id is unique only within a day, so dedupe on id together with its date or timestamp. Return 406 only for events you never want, because Mailgun won't send them again.

Questions

Where do I find the Mailgun webhook signing key?

In the Mailgun control panel under Settings › API Security, as the HTTP webhook signing key. It is account-wide and different from your API key; you can rotate it there.

Why does my Mailgun webhook signature never match?

Usually the wrong key (the API key instead of the webhook signing key), the values joined in the wrong order (it must be timestamp then token), or the hex digest compared in a different case or encoding.

Does Mailgun retry failed webhooks?

Yes, for any response other than 200 or 406, at growing intervals for up to 8 hours. Mailgun's docs say delivery notifications are the exception and aren't retried.

Do Mailgun webhooks cover inbound email?

No. Inbound mail is posted by a Route's forward() or store(notify=…) action. Those posts carry timestamp, token and signature as form fields and are verified with the same signing key and algorithm.

Sources