# Verify Mailgun webhooks

Mailgun signs every event webhook so you can confirm it came from Mailgun. There's no signature header: `signature.signature` in the JSON body is a hex HMAC-SHA256 of `signature.timestamp` followed by `signature.token`, with no separator, keyed with your account's Webhook Signing Key. The body isn't signed, so you can verify after parsing, but a valid signature doesn't show `event-data` is unchanged. Mailgun's Go SDK has a helper, `VerifyWebhookSignature`.

These pages cover event webhooks, which report on email you send. Inbound Routes, which post email you receive through `forward()` and `store()` actions, have no event types and are covered in [the Production guide](/webhooks/mailgun/guide-duplicates-ordering-retries-timeouts#inbound-routes).

Agent skill: `npx skills add hookdeck/webhook-skills --skill mailgun-webhooks` ([details](https://hookdeck.com/webhooks/mailgun/skill))

> Independent reference generated from hookdeck/webhook-registry (commit a24c8d9, 19 Nov 2026). [Mailgun's official docs](https://documentation.mailgun.com/docs/mailgun/user-manual/events/event-structure.md).

[Overview](https://hookdeck.com/webhooks/mailgun) · [Webhook events (9)](https://hookdeck.com/webhooks/mailgun/events) · [MCP events](https://hookdeck.com/webhooks/mailgun/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/mailgun/verify) · [Production guide](https://hookdeck.com/webhooks/mailgun/guide-duplicates-ordering-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/mailgun/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature field | `signature.signature` | [Mailgun docs](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks.md) |
| Scheme | `HMAC-SHA256, hex` | [Mailgun docs](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks.md) |
| Signed material | `{timestamp}{token}` signature.timestamp followed by signature.token, with no separator. event-data isn't signed. | [Mailgun docs](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks.md) |
| What to build | `Recompute the HMAC over signature.timestamp + signature.token, not the body, and compare` | [Mailgun docs](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks.md) |
| Key | `shared secret` | [Mailgun docs](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks.md) |

## Mailgun webhook secret

One Webhook Signing Key covers the whole account. It isn't your API key or a domain sending key. Keep it in an environment variable, not in source code.

- In the Control Panel: go to Settings, then API Security, then HTTP webhook signing key.
- Account-wide: a single key covers every domain, plus both event webhooks and Inbound Routes posts.
- Subaccounts: a delivery for a subaccount's domain also carries `signature.parent-signature`, computed the same way with the primary account's key, so you can verify with that one key.
- Rotation: you can rotate the key on the same page. The docs don't say whether the old key keeps working for a time.
- The docs describe no test and live split.

Source: [Mailgun docs](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks.md)

## Code

### Express

From [webhook-skills: skills/mailgun-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/mailgun-webhooks/examples/express/src/index.js)

```javascript
// Generated with: mailgun-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();
const port = process.env.PORT || 3000;

/**
 * Verify a Mailgun signature object.
 *
 * Mailgun puts the signature in the request BODY (not a header) as:
 *   { timestamp, token, signature }
 *
 * The signature is hex(HMAC-SHA256(signingKey, timestamp + token)).
 * For subaccount events a `parent-signature` field may also be present;
 * verify it with the parent account's signing key.
 */
function verifyMailgun(signature, signingKey) {
  if (!signature || !signingKey) return false;

  const { timestamp, token, signature: providedSig } = signature;
  if (!timestamp || !token || !providedSig) return false;

  const expected = crypto
    .createHmac('sha256', signingKey)
    .update(timestamp + token)
    .digest('hex');

  try {
    return crypto.timingSafeEqual(
      Buffer.from(expected, 'hex'),
      Buffer.from(providedSig, 'hex')
    );
  } catch {
    return false;
  }
}

// Health check
app.get('/health', (req, res) => res.json({ status: 'ok' }));

// Mailgun webhook endpoint
// Standard JSON parsing is fine — the signature only covers timestamp+token,
// not the request body, so we don't need raw bytes here.
app.post('/webhooks/mailgun', express.json(), (req, res) => {
  const signingKey = process.env.MAILGUN_WEBHOOK_SIGNING_KEY;
  if (!signingKey) {
    console.error('MAILGUN_WEBHOOK_SIGNING_KEY not configured');
    return res.status(500).json({ error: 'Webhook verification not configured' });
  }

  const signature = req.body && req.body.signature;
  if (!signature) {
    return res.status(400).json({ error: 'Missing signature in request body' });
  }

  if (!verifyMailgun(signature, signingKey)) {
    return res.status(400).json({ error: 'Invalid signature' });
  }

  // Optional: subaccount parent-signature verification
  const parentKey = process.env.MAILGUN_PARENT_WEBHOOK_SIGNING_KEY;
  if (signature['parent-signature'] && parentKey) {
    const parentExpected = crypto
      .createHmac('sha256', parentKey)
      .update(signature.timestamp + signature.token)
      .digest('hex');
    const parentSig = signature['parent-signature'];
    let parentOk = false;
    try {
      parentOk = crypto.timingSafeEqual(
        Buffer.from(parentExpected, 'hex'),
        Buffer.from(parentSig, 'hex')
      );
    } catch {
      parentOk = false;
    }
    if (!parentOk) {
      return res.status(400).json({ error: 'Invalid parent-signature' });
    }
  }

  const eventData = req.body['event-data'];
  if (!eventData || !eventData.event) {
    return res.status(400).json({ error: 'Missing event-data' });
  }

  // Dispatch on event type
  switch (eventData.event) {
    case 'accepted':
      console.log(`Accepted: ${eventData.recipient}`);
      break;

    case 'rejected':
      console.log(`Rejected: ${eventData.recipient} - ${eventData.reject && eventData.reject.reason}`);
      break;

    case 'delivered':
      console.log(`Delivered: ${eventData.recipient}`);
      // Your code: mark message as delivered in your database
      break;

    case 'failed':
      // severity is 'permanent' (hard bounce) or 'temporary' (soft bounce)
      console.log(`Failed (${eventData.severity}): ${eventData.recipient}`);
      if (eventData.severity === 'permanent') {
        // Your code: add address to your local suppression list
      }
      break;

    case 'opened':
      console.log(`Opened: ${eventData.recipient}`);
      // Your code: record engagement
      break;

    case 'clicked':
      console.log(`Clicked: ${eventData.recipient} -> ${eventData.url}`);
      // Your code: record click analytics
      break;

    case 'unsubscribed':
      console.log(`Unsubscribed: ${eventData.recipient}`);
      // Your code: remove from mailing list
      break;

    case 'complained':
      console.log(`Complained (spam): ${eventData.recipient}`);
      // Your code: add to suppression list
      break;

    case 'stored':
      console.log(`Stored inbound message at ${eventData.storage && eventData.storage.url}`);
      break;

    case 'list_member_uploaded':
      console.log(`List member uploaded: ${eventData.member && eventData.member.address}`);
      break;

    default:
      console.log(`Unhandled event type: ${eventData.event}`);
  }

  res.json({ received: true });
});

module.exports = app;

if (require.main === module) {
  app.listen(port, () => {
    console.log(`Mailgun webhook server listening on port ${port}`);
    console.log(`Webhook endpoint: http://localhost:${port}/webhooks/mailgun`);
  });
}
```

### Next.js

From [webhook-skills: skills/mailgun-webhooks/examples/nextjs/app/webhooks/mailgun/route.ts](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/mailgun-webhooks/examples/nextjs/app/webhooks/mailgun/route.ts)

```typescript
// Generated with: mailgun-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { createHmac, timingSafeEqual } from 'crypto';

interface MailgunSignature {
  timestamp: string;
  token: string;
  signature: string;
  'parent-signature'?: string;
}

interface MailgunEventData {
  event: string;
  recipient?: string;
  severity?: 'permanent' | 'temporary';
  url?: string;
  reject?: { reason?: string; description?: string };
  storage?: { url?: string; key?: string };
  [key: string]: unknown;
}

interface MailgunPayload {
  signature: MailgunSignature;
  'event-data': MailgunEventData;
}

/**
 * Verify a Mailgun signature object.
 * The signed content is `timestamp + token` (no separator), hashed with HMAC-SHA256.
 */
function verifyMailgun(signature: MailgunSignature, signingKey: string): boolean {
  if (!signature) return false;

  const { timestamp, token, signature: providedSig } = signature;
  if (!timestamp || !token || !providedSig) return false;

  const expected = createHmac('sha256', signingKey)
    .update(timestamp + token)
    .digest('hex');

  try {
    return timingSafeEqual(
      Buffer.from(expected, 'hex'),
      Buffer.from(providedSig, 'hex')
    );
  } catch {
    return false;
  }
}

function verifyParentSignature(
  signature: MailgunSignature,
  parentSigningKey: string
): boolean {
  const parentSig = signature['parent-signature'];
  if (!parentSig) return true;  // not a subaccount event — nothing to verify

  const expected = createHmac('sha256', parentSigningKey)
    .update(signature.timestamp + signature.token)
    .digest('hex');

  try {
    return timingSafeEqual(
      Buffer.from(expected, 'hex'),
      Buffer.from(parentSig, 'hex')
    );
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  const signingKey = process.env.MAILGUN_WEBHOOK_SIGNING_KEY;
  if (!signingKey) {
    console.error('MAILGUN_WEBHOOK_SIGNING_KEY not configured');
    return NextResponse.json(
      { error: 'Webhook verification not configured' },
      { status: 500 }
    );
  }

  let payload: MailgunPayload;
  try {
    payload = (await request.json()) as MailgunPayload;
  } catch {
    return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
  }

  const signature = payload?.signature;
  if (!signature) {
    return NextResponse.json(
      { error: 'Missing signature in request body' },
      { status: 400 }
    );
  }

  if (!verifyMailgun(signature, signingKey)) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  // Optional subaccount parent-signature verification
  const parentKey = process.env.MAILGUN_PARENT_WEBHOOK_SIGNING_KEY;
  if (signature['parent-signature'] && parentKey) {
    if (!verifyParentSignature(signature, parentKey)) {
      return NextResponse.json({ error: 'Invalid parent-signature' }, { status: 400 });
    }
  }

  const eventData = payload['event-data'];
  if (!eventData || !eventData.event) {
    return NextResponse.json({ error: 'Missing event-data' }, { status: 400 });
  }

  switch (eventData.event) {
    case 'accepted':
      console.log(`Accepted: ${eventData.recipient}`);
      break;

    case 'rejected':
      console.log(`Rejected: ${eventData.recipient} - ${eventData.reject?.reason}`);
      break;

    case 'delivered':
      console.log(`Delivered: ${eventData.recipient}`);
      // Mark message as delivered in your database
      break;

    case 'failed':
      // severity is 'permanent' (hard bounce) or 'temporary' (soft bounce)
      console.log(`Failed (${eventData.severity}): ${eventData.recipient}`);
      if (eventData.severity === 'permanent') {
        // Add address to your local suppression list
      }
      break;

    case 'opened':
      console.log(`Opened: ${eventData.recipient}`);
      break;

    case 'clicked':
      console.log(`Clicked: ${eventData.recipient} -> ${eventData.url}`);
      break;

    case 'unsubscribed':
      console.log(`Unsubscribed: ${eventData.recipient}`);
      break;

    case 'complained':
      console.log(`Complained (spam): ${eventData.recipient}`);
      break;

    case 'stored':
      console.log(`Stored inbound message at ${eventData.storage?.url}`);
      break;

    case 'list_member_uploaded':
      console.log('List member uploaded');
      break;

    default:
      console.log(`Unhandled event type: ${eventData.event}`);
  }

  return NextResponse.json({ received: true }, { status: 200 });
}

export async function GET() {
  return NextResponse.json({ status: 'ok', endpoint: '/webhooks/mailgun' });
}
```

### FastAPI

From [webhook-skills: skills/mailgun-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/mailgun-webhooks/examples/fastapi/main.py)

```python
# Generated with: mailgun-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
from typing import Any, Dict, Optional

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse

try:
    from dotenv import load_dotenv

    load_dotenv()
except ImportError:
    # dotenv is optional in production
    pass

app = FastAPI(title="Mailgun Webhook Handler")


def verify_mailgun(signature: Dict[str, Any], signing_key: str) -> bool:
    """Verify a Mailgun `signature` object.

    The signed content is the raw concatenation `timestamp + token` (no
    separator), hashed with HMAC-SHA256 and hex-encoded. Compare with the
    `signature` field using a timing-safe comparison.
    """
    if not signature or not signing_key:
        return False

    timestamp = signature.get("timestamp")
    token = signature.get("token")
    provided = signature.get("signature")

    if not (timestamp and token and provided):
        return False

    expected = hmac.new(
        signing_key.encode(),
        (str(timestamp) + str(token)).encode(),
        hashlib.sha256,
    ).hexdigest()

    return hmac.compare_digest(expected, provided)


def verify_parent_signature(
    signature: Dict[str, Any], parent_signing_key: str
) -> bool:
    """Verify the optional `parent-signature` field for subaccount webhooks.

    Returns True when no parent-signature is present (nothing to verify).
    """
    parent_sig = signature.get("parent-signature")
    if not parent_sig:
        return True

    timestamp = signature.get("timestamp", "")
    token = signature.get("token", "")

    expected = hmac.new(
        parent_signing_key.encode(),
        (str(timestamp) + str(token)).encode(),
        hashlib.sha256,
    ).hexdigest()

    return hmac.compare_digest(expected, parent_sig)


@app.get("/health")
async def health_check():
    return {"status": "ok"}


@app.post("/webhooks/mailgun")
async def handle_mailgun_webhook(request: Request):
    signing_key = os.getenv("MAILGUN_WEBHOOK_SIGNING_KEY")
    if not signing_key:
        raise HTTPException(
            status_code=500, detail="Webhook verification not configured"
        )

    body_bytes = await request.body()
    try:
        payload = json.loads(body_bytes)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON payload")

    signature: Optional[Dict[str, Any]] = payload.get("signature")
    if not signature:
        raise HTTPException(
            status_code=400, detail="Missing signature in request body"
        )

    if not verify_mailgun(signature, signing_key):
        raise HTTPException(status_code=400, detail="Invalid signature")

    parent_key = os.getenv("MAILGUN_PARENT_WEBHOOK_SIGNING_KEY")
    if signature.get("parent-signature") and parent_key:
        if not verify_parent_signature(signature, parent_key):
            raise HTTPException(
                status_code=400, detail="Invalid parent-signature"
            )

    event_data = payload.get("event-data")
    if not event_data or not event_data.get("event"):
        raise HTTPException(status_code=400, detail="Missing event-data")

    event = event_data["event"]
    recipient = event_data.get("recipient")

    if event == "accepted":
        print(f"Accepted: {recipient}")
    elif event == "rejected":
        reason = (event_data.get("reject") or {}).get("reason")
        print(f"Rejected: {recipient} - {reason}")
    elif event == "delivered":
        print(f"Delivered: {recipient}")
        # Mark message as delivered in your database
    elif event == "failed":
        # severity is 'permanent' (hard bounce) or 'temporary' (soft bounce)
        severity = event_data.get("severity")
        print(f"Failed ({severity}): {recipient}")
        if severity == "permanent":
            # Add address to your local suppression list
            pass
    elif event == "opened":
        print(f"Opened: {recipient}")
    elif event == "clicked":
        print(f"Clicked: {recipient} -> {event_data.get('url')}")
    elif event == "unsubscribed":
        print(f"Unsubscribed: {recipient}")
    elif event == "complained":
        print(f"Complained (spam): {recipient}")
    elif event == "stored":
        storage = event_data.get("storage") or {}
        print(f"Stored inbound message at {storage.get('url')}")
    elif event == "list_member_uploaded":
        print("List member uploaded")
    else:
        print(f"Unhandled event type: {event}")

    return JSONResponse(content={"received": True}, status_code=200)


if __name__ == "__main__":
    import uvicorn

    port = int(os.getenv("PORT", 3000))
    uvicorn.run(app, host="0.0.0.0", port=port)
```

Or install the Mailgun webhooks skill: `npx skills add hookdeck/webhook-skills --skill mailgun-webhooks`

## Common failures

- **API key instead of the signing key.** The key is the HTTP webhook signing key under Settings, then API Security. It isn't your API key or a domain sending key.
- **Subaccount events checked with the primary key.** With only your primary account's key, verify `signature.parent-signature`. Mailgun adds it to events for a subaccount's domain so you don't need each subaccount's key.
- **Timestamp check too strict.** Mailgun says webhook processing can be delayed for reasons outside its control, so don't be too aggressive when comparing `timestamp` with the current time.
- **A different Mailgun webhook.** Inbound Routes send `timestamp`, `token` and `signature` as top-level form fields. A route URL ending in `json` uses `X-Mailgun-` headers and signs the body in place of `token`. Alert webhooks use `X-Sign`, sign the whole body and have their own key. Older legacy webhooks post form fields with a top-level `event`, and Mailgun says they all need migrating.

From [Hookdeck's Mailgun guide](https://hookdeck.com/webhooks/mailgun/guide-duplicates-ordering-retries-timeouts).

---

Not affiliated with Mailgun. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/mailgun.json) · [Report a correction](https://hookdeck.com/contact)
