twilio-sendgrid-webhooks
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 analytic
- 0
- Installs
- —
- Rating
- —
- Success rate
- 2
- Files scanned
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 97cdb1be5c7c7291… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
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
| Event | Meaning |
|---|---|
processed | SendGrid accepted and will attempt delivery |
deferred | Temporary failure — SendGrid will retry |
delivered | Recipient's mail server accepted the message |
bounce | Permanent failure — address invalid or rejected |
dropped | SendGrid will not deliver (suppression, invalid, spam) |
Engagement Events
| Event | Meaning |
|---|---|
open | Recipient opened (pixel-based — unreliable) |
click | Recipient clicked a tracked link |
spamreport | Recipient marked as spam |
unsubscribe | Recipient clicked unsubscribe link |
group_unsubscribe | Recipient unsubscribed from ASM group |
group_resubscribe | Recipient 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)
from flask import Flask, request
app = 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)
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:
| Method | How 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.0 | SendGrid 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
reasonoriginate 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
Files
2- SKILL.md
24f3cad2115.7 KB - agents/openai.yaml
f77c52c485457 B
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from twilio/ai8
Create and configure a Twilio account from scratch. Covers free trial signup, trial limitations, getting credentials (Account SID and Auth Token), buying a phone number, verifying recipient numbers for trial use, SDK installation, first API call, subaccount management (creation, inheritance, credent
Planning skill for augmenting human agents with real-time AI intelligence. Qualifies the developer's use case across coaching, compliance, QA, and routing to recommend the right Conversation Intelligence + Conversation Memory + TaskRouter architecture. Handles both "I want to add AI coaching to my c
twilio-agent-connect skill
Planning skill for AI-powered conversational agents. Qualifies the developer's use case across outcome sophistication, entry point, and customer profile to recommend the right Twilio Conversations architecture and implementation skills. Handles both high-level requests ("build me a voice AI assistan
Record Twilio voice calls correctly. Covers the critical distinction between Record verb (voicemail) and Dial record (call recording), dual-channel for QA, mid-call pause for PCI, Conference recording, and the ConversationRelay workaround. Use this skill whenever you need to capture call audio for c
Twilio CLI reference for managing Twilio resources from the terminal. Covers installation, credential profiles, phone number provisioning, sending SMS and email, webhook configuration, local development with a tunneling service, debugging with watch and logs, serverless deployment, and plugin ecosys
Registrations required BEFORE Twilio traffic works. Covers messaging programs (A2P 10DLC, toll-free verification, WhatsApp WABA, RCS, short code, alphanumeric sender) and voice trust programs (STIR/SHAKEN, Voice Integrity, Branded Calling, CNAM). Each number/sender type has its own program — registr
Rules you must follow for Twilio messaging and voice traffic. Covers TCPA (consent tiers, quiet hours, DNC), GDPR (EU consent, right to deletion), PCI DSS (payment recording, Pay verb), HIPAA (BAA, PHI), FDCPA (debt collection limits), CAN-SPAM, WhatsApp policies, SHAKEN/STIR, and consent management
Related backend skillsscan passed
PostHog error tracking for Node.js
Handle FormData, file uploads, Blob, Uint8Array, and ReadableStream inputs in tRPC mutations. Use octetInputParser from @trpc/server/http for binary data. Route non-JSON requests with splitLink and isNonJsonSerializable() from @trpc/client. FormData and binary inputs only work with mutations (POST).
Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.
Django architecture patterns, REST API design with DRF, ORM best practices, caching, signals, middleware, and production-grade Django apps. Use when building or reviewing Django apps, DRF APIs, ORM queries, or caching.
Guide for upgrading Stripe API versions, webhook endpoints, server-side SDKs, Stripe.js, and mobile SDKs
Deploys a Regional REST API with a custom domain name, a Lambda backend function, and a request-based Lambda authorizer using AWS CLI. Covers ACM certificate provisioning, API Gateway REST API creation, Lambda function deployment, request authorizer setup, custom domain configuration, base path mapp