Twilio Sendgrid Webhooks

作者 twilio8aba46fb65dc無授權條款收錄於 2026年10月8日更新於 2026年10月8日

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 產生的概覽

指導實作 SendGrid 事件 Webhook,用於追蹤郵件送達、互動、退信及簽章驗證。

功能
此技能說明如何接收與處理 SendGrid 事件 Webhook,涵蓋全部 11 種送達與互動事件類型。它提供 Python(Flask)與 Node.js(Express)的處理程式範例,用來解析批次事件陣列並回傳 2xx 確認回應。它也記錄了 ECDSA 簽章驗證、OAuth 2.0 驗證、重試與去重行為、多個 Webhook 端點,以及開啟追蹤不可靠等已知限制。
適用情境
適用於建置依賴非同步事件通知的 SendGrid 送達追蹤、互動分析或退信處理。也適合需要實作或除錯 Webhook 端點、驗證 Webhook 真偽或解讀 SendGrid 事件內容的場合。
執行需求
需要帶有 SG. 前綴的 SendGrid API 金鑰;不適用於 Twilio Email API。Webhook 端點需要可公開存取的 HTTP 伺服器,驗證時還需要簽章事件 Webhook 驗證金鑰或 OAuth 2.0 授權伺服器。僅為說明文件,未附帶指令碼。

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

來源與署名

來源:twilio/ai位於skills/sendgrid/twilio-sendgrid-webhooks提交8aba46f

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 twilio/ai 的技能

Twilio Voice Twiml

twilio

使用 TwiML 建構 Twilio 語音通話邏輯,涵蓋核心動詞、SDK 產生方式和 IVR 範例。

Software Development2026年10月8日

Twilio Isv Sms Best Practices

twilio

給 ISV 的多租戶 Twilio SMS 建置指南,涵蓋 A2P 與免付費號碼註冊、子帳戶及常見陷阱。

Software Development2026年10月8日

Twilio Security Compliance Hipaa

twilio

指導為 HIPAA 合規設定 Twilio 帳戶,涵蓋 BAA、HIPAA 專案指定、合格服務及各產品要求。

Security2026年10月8日

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.

待分類2026年10月8日

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.

待分類2026年10月8日

Twilio Numbers Senders

twilio

指導在開發前選擇合適的 Twilio 號碼類型和傳送者,涵蓋合規計畫、輸送量和可用性。

Communication2026年10月8日