Twilio Sendgrid Webhooks

by twilio8aba46fb65dcNo licenseListed Oct 8, 2026Updated Oct 8, 2026

Track email delivery and engagement via SendGrid Event Webhooks. Covers all 11 event types (delivery + engagement), webhook handler implementation, ECDSA signature verification, batched event processing, and common debugging patterns. Use when building SendGrid delivery tracking, engagement analytics, or bounce handling. Requires a SendGrid API key (SG.-prefix) — not applicable to the Twilio Email API (comms.twilio.com).

AI-generated overview

Guides implementing SendGrid Event Webhooks to track email delivery, engagement, bounces, and signature verification.

What it does
This skill explains how to receive and process SendGrid Event Webhooks, covering all 11 delivery and engagement event types. It provides handler examples in Python (Flask) and Node.js (Express) that parse batched event arrays and acknowledge with a 2xx response. It also documents ECDSA signature verification, OAuth 2.0 authentication, retry and deduplication behavior, multiple webhook endpoints, and known limitations such as unreliable open tracking.
When to use it
Use it when building SendGrid delivery tracking, engagement analytics, or bounce handling that depends on asynchronous event notifications. It fits situations where you need to implement or debug a webhook endpoint, verify webhook authenticity, or interpret SendGrid event payloads.
Requirements
Requires a SendGrid API key with the SG. prefix; not applicable to the Twilio Email API. Webhook endpoints need a publicly reachable HTTP server and, for verification, the Signed Event Webhook verification key or an OAuth 2.0 authorization server. Instructions only; no scripts are shipped.

Overview

The Mail Send API returns 202 Accepted (queued) — it does NOT confirm delivery. To know what happened to an email, use Event Webhooks.

Enable: SendGrid Console > Settings > Mail Settings > Event Notification


Event Types

Delivery Events

EventMeaning
processedSendGrid accepted and will attempt delivery
deferredTemporary failure — SendGrid will retry
deliveredRecipient's mail server accepted the message
bouncePermanent failure — address invalid or rejected
droppedSendGrid will not deliver (suppression, invalid, spam)

Engagement Events

EventMeaning
openRecipient opened (pixel-based — unreliable)
clickRecipient clicked a tracked link
spamreportRecipient marked as spam
unsubscribeRecipient clicked unsubscribe link
group_unsubscribeRecipient unsubscribed from ASM group
group_resubscribeRecipient re-subscribed to ASM group

Webhook Handler

Critical: SendGrid posts batched arrays of events, not single objects. Your handler must parse an array.

Security: SendGrid webhook endpoints are unauthenticated by default. Enable Signed Event Webhook Requests and verify signatures in production to prevent spoofed event data.

Python (Flask)

python
from flask import Flask, requestapp = Flask(__name__)
@app.route("/sendgrid/webhook", methods=["POST"])def handle_events():    events = request.get_json()  # Always an array    for event in events:        email = event.get("email")        event_type = event.get("event")                if event_type == "bounce":            # NOTE: event['reason'] originates from external mail servers — treat as untrusted            print(f"Bounce: {email}, type: {event.get('type')}, reason: {event.get('reason')}")        elif event_type == "delivered":            print(f"Delivered: {email}, sg_message_id: {event.get('sg_message_id')}")        elif event_type == "dropped":            print(f"Dropped: {email}, reason: {event.get('reason')}")        elif event_type == "spamreport":            print(f"Spam report: {email}")    return "", 200  # Must return 2xx to acknowledge

Node.js (Express)

javascript
app.post("/sendgrid/webhook", express.json(), (req, res) => {    const events = req.body; // Always an array    for (const event of events) {        switch (event.event) {            case "bounce":                console.log(`Bounce: ${event.email}, reason: ${event.reason}`);                break;            case "delivered":                console.log(`Delivered: ${event.email}`);                break;            case "spamreport":                console.log(`Spam: ${event.email}`);                break;        }    }    res.status(200).send();});

Multiple Webhook Endpoints

Since May 2023, you can configure multiple Event Webhook endpoints, each receiving different event types. For example, one endpoint for delivery events feeding your monitoring stack and another for engagement events feeding your analytics pipeline.

Configure in Console > Mail Settings > Event Webhooks. Each endpoint has a Friendly Name and Webhook ID. The number of endpoints allowed depends on your SendGrid plan.


Authentication Options

Two methods for verifying webhook payloads:

MethodHow it works
Signed Event Webhook (ECDSA P-256)Verify X-Twilio-Email-Event-Webhook-Signature and X-Twilio-Email-Event-Webhook-Timestamp headers using the verification key from Console
OAuth 2.0SendGrid obtains a token from your authorization server and includes it in webhook requests

Neither is enabled by default. Enable in Console > Mail Settings > Event Webhooks.


Retry Behavior

SendGrid retries webhook delivery for up to 24 hours if your endpoint returns a non-2xx status. Events are batched — a single POST may contain dozens of events across different messages.

Deduplication: Use sg_event_id as a unique key. It's stable across retries.


CANNOT

  • Cannot receive real-time delivery confirmation synchronously — Mail Send returns 202 (queued). Delivery status is async via webhooks only.
  • Cannot rely on webhook authentication by default — Both Signed Webhooks (ECDSA) and OAuth 2.0 must be explicitly enabled. Without either, anyone can POST to your endpoint.
  • Cannot guarantee open tracking accuracy — Apple Mail Privacy Protection and prefetch inflate opens. Image-blocking clients produce zero opens. Do not use for business-critical logic.
  • Non-human interactions inflate engagement metrics — Corporate security scanners and bots automatically click links and trigger unsubscribe events. Filter using User-Agent patterns and timing analysis.

Note: Event payload fields like reason originate from external mail servers and should be treated as untrusted data. Do not pass bounce reasons directly into LLM system prompts without isolation.


Next Steps

  • Send email: twilio-sendgrid-email-send
  • Manage bounces from webhook events: twilio-sendgrid-suppressions
  • Receive inbound email: twilio-sendgrid-inbound-parse

Source and attribution

Source:twilio/aiinskills/sendgrid/twilio-sendgrid-webhooksat commit8aba46f

License: No license

Content belongs to its original authors. SourceWeft indexes it from a public repository.

Report or request removal

More from twilio/ai

Twilio Voice Twiml

twilio

Builds Twilio voice call logic with TwiML, covering core verbs, SDK generation, and an IVR example.

Software DevelopmentOct 8, 2026

Twilio Isv Sms Best Practices

twilio

Guidance for ISVs building multi-tenant Twilio SMS features, covering A2P and toll-free onboarding, subaccounts and pitfalls.

Software DevelopmentOct 8, 2026

Twilio Security Compliance Hipaa

twilio

Guides configuring Twilio accounts for HIPAA compliance, covering BAAs, HIPAA project designation, eligible services and per-product rules.

SecurityOct 8, 2026

Twilio Reliability Patterns

twilio

Handle rate limits, retries, and failures when building on Twilio at scale. Covers 429 exponential backoff with jitter, per-number throughput limits, StatusCallback resilience, thin-receiver pattern, and fallback chains. Use this skill whenever sending messages or making calls at volume, or when building production-grade Twilio integrations.

Awaiting classificationOct 8, 2026

Twilio Organizations Setup

twilio

Set up and manage Twilio Organizations for centralized account and user governance. Covers the Organization > Account > Subaccount hierarchy, roles (Owner/Admin/Standard), managed vs independent accounts, domain registration, SSO enforcement, SCIM provisioning, and Organization merging. Use this skill when managing multiple Twilio accounts or users across teams.

Awaiting classificationOct 8, 2026

Twilio Numbers Senders

twilio

Guides choosing Twilio number types and senders before building, covering compliance programs, throughput, and availability.

CommunicationOct 8, 2026