MessagePit now catches mail sent through SendGrid's API
MessagePit is a fork of Mailpit, a tool whose entire job is catching email. Until tonight it still couldn’t catch the email a lot of apps send.
Earlier today I wrote about catching Twilio SMS locally and closed by asking which API in your stack you’re still mocking. For a lot of apps, the answer is the email one.
Mailpit catches SMTP. Plenty of apps never speak SMTP. They send through SendGrid’s v3 Mail Send API, an HTTPS POST with a JSON body and a Bearer token, because that’s what the production integration uses. Point that client at port 1025 and you get a protocol mismatch, not an email. So in dev the options were the same three bad ones as with SMS: stub the mailer, swap in a different delivery method for development, or send real mail through a real SendGrid account. Every one of those means the code path you run locally isn’t the one you ship.
So MessagePit now speaks SendGrid’s HTTP API too.
One Endpoint
The stub is a single route on the existing web server, the same port 8025 that serves the UI:
POST /v3/mail/send
Authorization: Bearer <MP_SENDGRID_API_KEY>
Content-Type: application/jsonAuth is opt-in, the same way the Twilio side works. If MP_SENDGRID_API_KEY (or --sendgrid-api-key) is set, the Authorization header has to carry that exact Bearer token or the request gets a 401. Leave it empty and the stub accepts anything. That’s fine on a laptop. Set it the moment MessagePit is reachable from anywhere else, and remember the token travels over plain HTTP, so it keeps out casual traffic rather than a determined one.
From the shell:
curl -i http://localhost:8025/v3/mail/send \
-H "Authorization: Bearer test" \
-H "Content-Type: application/json" \
-d '{
"from": {"email": "app@example.com", "name": "Example App"},
"subject": "Your login code",
"personalizations": [
{"to": [{"email": "user@example.com"}],
"custom_args": {"notification_id": "n_123"}}
],
"content": [
{"type": "text/plain", "value": "Your code is 424242"},
{"type": "text/html", "value": "<p>Your code is <b>424242</b></p>"}
]
}'It answers 202 Accepted with no body, which is what real SendGrid does, so client libraries that check for a 2xx are happy. Open http://localhost:8025 and the message is in the inbox alongside everything that arrived over SMTP.
From an application, any SendGrid client that lets you override the API base URL works the same way: point it at http://localhost:8025 in development and leave the default in production. The Rails guide walks through that for sendgrid-actionmailer.
Turning JSON Back Into Email
The interesting design decision is where the stub plugs in. Mailpit’s storage layer, storage.Store, takes raw RFC 5322 message bytes, the same thing the SMTP server hands it. Everything downstream (parsing, search, tagging, the WebSocket live updates, the existing webhooks) hangs off that one function.
So the SendGrid handler doesn’t get its own table or its own UI. It rebuilds a MIME message from the JSON and hands it to the same Store the SMTP server uses:
for _, p := range msg.Personalizations {
merged := mergeArgs(msg.CustomArgs, p.CustomArgs) // personalization wins
notificationID := merged["notification_id"]
for _, to := range p.To {
raw := buildMIME(&msg, &p, to, notificationID)
storage.Store(&raw, &username) // username = "sendgrid"
}
}
w.WriteHeader(http.StatusAccepted)(Trimmed. The real loop inlines the merge and logs store errors.)
A few mapping rules fall out of that:
- One stored message per
torecipient. SendGrid fans a personalization out to each recipient, so the stub does too. Each copy gets its ownTo:header. ccbecomes aCc:header on each copy, but cc recipients don’t get a stored copy of their own. Search the inbox for a cc address and you’ll find it only in that header.contentdecides the body. One entry becomes a single-part body with that content type; two or more becomemultipart/alternative, which is how you get the text and HTML views in the viewer.- Top-level
headersare copied through onto the message. custom_argsmerge, message-level first, personalization-level overriding. If the result has anotification_id, it’s written into the message as anX-Notification-Idheader.- The message is stored with the username
sendgrid, the same field Mailpit fills in from SMTP auth, so API traffic is labelled as such.
A request missing from.email, subject, or personalizations gets a 400 with an empty body. There’s no SendGrid-style errors array yet.
Delivery Webhooks
Catching the send is half the integration. The other half is SendGrid’s Event Webhook: SendGrid POSTs delivery events back to your app, and your app updates a notification record, marks something delivered, retries something else. That code is just as untested in dev as the sending code was.
The X-Notification-Id header is the hook for that. When MP_EMAIL_WEBHOOK_URL is set, the storage path checks every newly stored message for that header and, if it’s there, fires a SendGrid-style event at your URL in the background.
Putting that check in storage rather than in the SendGrid handler was deliberate. The handler’s only job is translating JSON into a message. Anything that reacts to “a message arrived” lives with the other things that react to it. One consequence worth knowing: the trigger is the header, not the endpoint, so a message that arrives over SMTP with an X-Notification-Id header set fires the same webhook.
The payload is a JSON array with one event:
[
{
"notification_id": "n_123",
"event": "delivered",
"email": "user@example.com",
"timestamp": 1777338000
}
]That’s the whole lifecycle for now: one delivered event per stored copy that carries a notification_id. No processed, no bounces, no opens. It’s enough to drive “did my app record that this email went out?” end to end, which was the gap I needed to close.
Signed Like the Real Thing
SendGrid signs its event webhooks with ECDSA, and your production handler should be verifying that signature. A local webhook that skips it would mean your verification code is the one part you never exercise.
So MessagePit signs them the same way. It takes the timestamp string, appends the raw JSON body, hashes with SHA-256, signs with an ECDSA P-256 key, and sends the result in the headers SendGrid uses. (SendGrid is a Twilio company, hence the names.)
X-Twilio-Email-Event-Webhook-Signature: base64-encoded signatureX-Twilio-Email-Event-Webhook-Timestamp: Unix timestamp
Verifying it in Go:
func verifyEvent(pub *ecdsa.PublicKey, r *http.Request, body []byte) bool {
sig, err := base64.StdEncoding.DecodeString(
r.Header.Get("X-Twilio-Email-Event-Webhook-Signature"))
if err != nil {
return false
}
ts := r.Header.Get("X-Twilio-Email-Event-Webhook-Timestamp")
hash := sha256.Sum256(append([]byte(ts), body...))
return ecdsa.VerifyASN1(pub, hash[:], sig)
}That checks the signature only. A production handler should also reject timestamps outside a small window, so a captured event can’t be replayed later.
The private key comes from MP_EMAIL_WEBHOOK_SIGNING_KEY as base64-encoded SEC1 DER, and your app needs the matching public key as base64 PKIX DER (what x509.ParsePKIXPublicKey expects). To make a pair:
openssl ecparam -name prime256v1 -genkey -noout -outform DER -out webhook-key.der
base64 < webhook-key.der # MP_EMAIL_WEBHOOK_SIGNING_KEY
openssl ec -inform DER -in webhook-key.der -pubout -outform DER | base64 # your app's public keyThis is a throwaway dev key. It’s fine in a compose file, and it should never be anything SendGrid issued.
If you don’t set a key, MessagePit generates a P-256 pair at startup and logs the public key. That’s handy for a one-off test and annoying everywhere else, because it changes on every restart.
What’s Not There Yet
As of tonight:
- One event type. Only
delivered, and only for messages with anotification_id. Real SendGrid sends far more than that. - Attachments, templates, and scheduled sends are dropped silently. Those fields aren’t in the request struct, so the request still gets a
202. A test that sends an attachment will “pass” here and lose the attachment without a word. That’s the sharpest edge in the stub. - No BCC copies. BCC recipients are parsed and ignored.
None of that blocks the use case I built it for: sending mail through the real SendGrid client in development and watching the delivery event come back, signed, to the real webhook handler.
The pattern from this morning’s post held up. Mailpit already had the inbox, storage, search, and live updates. The SendGrid stub is one handler that turns JSON into the bytes Mailpit already knew how to store, plus one hook that reacts when those bytes land.
The SendGrid docs page has the current setup in more detail.
What does your app assume about email delivery events that you’ve never actually watched happen?