$npx -y skills add hookdeck/webhook-skills --skill mailgun-webhooksReceive and verify Mailgun webhooks. Use when setting up Mailgun webhook handlers, debugging Mailgun signature verification, or handling email events like delivered, failed, opened, clicked, unsubscribed, and complained.
| 1 | # Mailgun Webhooks |
| 2 | |
| 3 | ## When to Use This Skill |
| 4 | |
| 5 | - Setting up Mailgun webhook handlers |
| 6 | - Verifying Mailgun webhook signatures (HMAC-SHA256 over `timestamp + token`) |
| 7 | - Debugging Mailgun signature verification failures |
| 8 | - Handling email delivery events: `delivered`, `failed`, `opened`, `clicked` |
| 9 | - Handling list events: `unsubscribed`, `complained` |
| 10 | - Distinguishing permanent vs temporary failures via the `severity` field |
| 11 | - Verifying subaccount webhooks via the optional `parent-signature` field |
| 12 | |
| 13 | ## How Mailgun Webhooks Differ |
| 14 | |
| 15 | Unlike most providers, **Mailgun puts the signature inside the request body**, not in a header. The webhook payload always has this shape: |
| 16 | |
| 17 | ```json |
| 18 | { |
| 19 | "signature": { |
| 20 | "timestamp": "1529006854", |
| 21 | "token": "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0", |
| 22 | "signature": "d2271d12299f6592d9d44cd9d250f0704e4674c30d79d07c47a66f95ce71cf55" |
| 23 | }, |
| 24 | "event-data": { "event": "delivered", "...": "..." } |
| 25 | } |
| 26 | ``` |
| 27 | |
| 28 | Verify by computing `HMAC-SHA256(signing_key, timestamp + token)` and comparing the hex digest to `signature.signature` using timing-safe equality. |
| 29 | |
| 30 | ## Essential Code (USE THIS) |
| 31 | |
| 32 | ### Node.js — Verify Signature |
| 33 | |
| 34 | ```javascript |
| 35 | const crypto = require('crypto'); |
| 36 | |
| 37 | function verifyMailgun(signature, signingKey) { |
| 38 | // signature is the `signature` object from the request body |
| 39 | const { timestamp, token, signature: providedSig } = signature; |
| 40 | |
| 41 | if (!timestamp || !token || !providedSig) return false; |
| 42 | |
| 43 | const expected = crypto |
| 44 | .createHmac('sha256', signingKey) |
| 45 | .update(timestamp + token) // concatenate, no separator |
| 46 | .digest('hex'); |
| 47 | |
| 48 | // Timing-safe comparison |
| 49 | try { |
| 50 | return crypto.timingSafeEqual( |
| 51 | Buffer.from(expected, 'hex'), |
| 52 | Buffer.from(providedSig, 'hex') |
| 53 | ); |
| 54 | } catch { |
| 55 | return false; // length mismatch |
| 56 | } |
| 57 | } |
| 58 | ``` |
| 59 | |
| 60 | ### Express Webhook Handler |
| 61 | |
| 62 | ```javascript |
| 63 | const express = require('express'); |
| 64 | const crypto = require('crypto'); |
| 65 | |
| 66 | const app = express(); |
| 67 | |
| 68 | app.post('/webhooks/mailgun', express.json(), (req, res) => { |
| 69 | const { signature, 'event-data': eventData } = req.body; |
| 70 | |
| 71 | if (!signature || !verifyMailgun(signature, process.env.MAILGUN_WEBHOOK_SIGNING_KEY)) { |
| 72 | return res.status(400).json({ error: 'Invalid signature' }); |
| 73 | } |
| 74 | |
| 75 | switch (eventData.event) { |
| 76 | case 'delivered': |
| 77 | console.log('Delivered:', eventData.recipient); |
| 78 | break; |
| 79 | case 'failed': |
| 80 | // severity: 'permanent' (hard bounce) or 'temporary' (soft bounce) |
| 81 | console.log(`Failed (${eventData.severity}):`, eventData.recipient); |
| 82 | break; |
| 83 | case 'opened': |
| 84 | console.log('Opened:', eventData.recipient); |
| 85 | break; |
| 86 | case 'clicked': |
| 87 | console.log('Clicked:', eventData.url); |
| 88 | break; |
| 89 | case 'unsubscribed': |
| 90 | case 'complained': |
| 91 | console.log(`${eventData.event}:`, eventData.recipient); |
| 92 | break; |
| 93 | } |
| 94 | |
| 95 | res.json({ received: true }); |
| 96 | }); |
| 97 | ``` |
| 98 | |
| 99 | ### Python (FastAPI) Webhook Handler |
| 100 | |
| 101 | ```python |
| 102 | import hmac, hashlib, os |
| 103 | from fastapi import FastAPI, Request, HTTPException |
| 104 | |
| 105 | app = FastAPI() |
| 106 | SIGNING_KEY = os.environ["MAILGUN_WEBHOOK_SIGNING_KEY"] |
| 107 | |
| 108 | def verify_mailgun(sig: dict) -> bool: |
| 109 | timestamp = sig.get("timestamp", "") |
| 110 | token = sig.get("token", "") |
| 111 | provided = sig.get("signature", "") |
| 112 | expected = hmac.new( |
| 113 | SIGNING_KEY.encode(), |
| 114 | (timestamp + token).encode(), |
| 115 | hashlib.sha256, |
| 116 | ).hexdigest() |
| 117 | return hmac.compare_digest(expected, provided) |
| 118 | |
| 119 | @app.post("/webhooks/mailgun") |
| 120 | async def mailgun_webhook(request: Request): |
| 121 | body = await request.json() |
| 122 | signature = body.get("signature") |
| 123 | if not signature or not verify_mailgun(signature): |
| 124 | raise HTTPException(status_code=400, detail="Invalid signature") |
| 125 | |
| 126 | event_data = body.get("event-data", {}) |
| 127 | # handle event_data["event"]... |
| 128 | return {"received": True} |
| 129 | ``` |
| 130 | |
| 131 | > **For complete working examples with tests**, see: |
| 132 | > - [examples/express/](examples/express/) - Full Express implementation |
| 133 | > - [examples/nextjs/](examples/nextjs/) - Next.js App Router implementation |
| 134 | > - [examples/fastapi/](examples/fastapi/) - Python FastAPI implementation |
| 135 | |
| 136 | ## Common Event Types |
| 137 | |
| 138 | | Event | Triggered When | Key Fields | |
| 139 | |-------|----------------|------------| |
| 140 | | `accepted` | Mailgun accepted the message for delivery | `recipient`, `message` | |
| 141 | | `rejected` | Mailgun rejected the message before delivery | `reason`, `reject` | |
| 142 | | `delivered` | Receiving server accepted the message | `recipient`, `delivery-status` | |
| 143 | | `failed` | Permanent or temporary delivery failure | `recipient`, `severity` (`permanent`/`temporary`), `delivery-status` | |
| 144 | | `opened` | Recipient opened the email (requires open tracking) | |