Send With Confidence
Partner with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.
Time to read: 2 minutes
using Newtonsoft.Json; | |
using System.Collections.Generic; | |
namespace SendGridEventWebhook.Models | |
{ | |
// This class models the data we POST from our Event Webhook stream | |
public class SendGridEvents | |
{ | |
// Docs: https://sendgrid.com/docs/API_Reference/Webhooks/event.html | |
public string email { get; set; } | |
public int timestamp { get; set; } | |
public int uid { get; set; } | |
public int id { get; set; } | |
public string sendgrid_event_id { get; set; } | |
[JsonProperty("smtp-id")] // switched to underscore for consistancy | |
public string smtp_id { get; set; } | |
public string sg_message_id { get; set; } | |
[JsonProperty("event")] // event is protected keyword | |
public string sendgrid_event { get; set; } | |
public string type { get; set; } | |
public IList<string> category { get; set; } | |
public string reason { get; set; } | |
public string status { get; set; } | |
public string url { get; set; } | |
public string useragent { get; set; } | |
public string ip { get; set; } | |
// Add your custom fields here | |
public string purchase { get; set; } // this is a custom field sent by our tester | |
} | |
} |
Partner with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.
using System.Collections.Generic; | |
using System.Web; | |
using System.Web.Mvc; | |
using SendGridEventWebhook.Models; | |
using Newtonsoft.Json; | |
namespace SendGridEventWebhook.Controllers | |
{ | |
// Display the default home page for this example | |
public class HomeController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
return View(); | |
} | |
} | |
// Capture the SendGrid Event Webhook POST's at the /api/SendGrid endpoint | |
public class apiController : Controller | |
{ | |
[HttpPost] | |
[ValidateInput(false)] | |
public ActionResult SendGrid() | |
{ | |
System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Request.InputStream); | |
string rawSendGridJSON = reader.ReadToEnd(); | |
List<SendGridEvents> sendGridEvents = JsonConvert.DeserializeObject<List<SendGridEvents>>(rawSendGridJSON); | |
string count = sendGridEvents.Count.ToString(); | |
System.Diagnostics.Trace.TraceError(rawSendGridJSON); // For debugging to the Azure Streaming logs | |
foreach (SendGridEvents sendGridEvent in sendGridEvents) | |
{ | |
// Here is where you capture the event data | |
System.Diagnostics.Trace.TraceError(sendGridEvent.email); // For debugging to the Azure Streaming logs | |
} | |
return new HttpStatusCodeResult(200); | |
} | |
} | |
} |