Sending an email via SparkPost in C#
By FoxLearn 1/15/2025 2:32:11 AM 91
Getting Started with SparkPost Email Templates
To send emails using SparkPost, you will first need to create an email template. The template is defined with placeholder tokens that will be replaced dynamically when sending an email. Tokens use the syntax {{tokenname}}
to indicate where dynamic content should be inserted.
For example, you might create a SparkPost template like this:
Hello {{firstName}} {{lastName}}, welcome to our service!
When sending the email, SparkPost will replace {{firstName}}
and {{lastName}}
with the actual data you provide for each recipient.
Sending an Email via the SparkPost API
To send an email, you interact with the SparkPost API. This involves submitting a JSON document containing essential information, such as the recipient's email address, the template name, and any dynamic data for token replacement.
Here's how you can structure the JSON body for sending an email:
{ "campaign_id": "myCampaign", "recipients": [ { "address": "[email protected]", "substitution_data": { "email": "[email protected]", "firstname": "Brian", "lastname": "Pedersen" } } ], "content": { "template_id": "my-first-email" } }
Creating the JSON Body
To build the JSON body programmatically, we can use a simple method that constructs the JSON structure by inserting the dynamic data. The following example uses StringBuilder
to generate the necessary JSON:
public byte[] CreateJsonBody(string templateName, string campaignID, string email, string firstName, string lastName) { var jsonBody = $@" {{ ""campaign_id"": ""{campaignID}"", ""recipients"": [ {{ ""address"": ""{email}"", ""substitution_data"": {{ ""email"": ""{email}"", ""firstname"": ""{firstName}"", ""lastname"": ""{lastName}"" }} }} ], ""content"": {{ ""template_id"": ""{templateName}"" }} }}"; return Encoding.UTF8.GetBytes(jsonBody); }
Sending the Email
Once the JSON body is ready, the next step is to send the email by making a POST request to SparkPost's API endpoint. Below is a simple implementation of a service class to interact with the SparkPost API:
using System; using System.IO; using System.Net; using System.Text; namespace MyNamespace { public class SparkPostService { private readonly string _SPARKPOSTURL = "https://api.sparkpost.com/api/v1/transmissions?num_rcpt_errors=3"; private readonly string _sparkPostAuthorizationKey; public SparkPostService(string sparkPostAuthorizationKey) { _sparkPostAuthorizationKey = sparkPostAuthorizationKey; } public string SendEmail(byte[] jsonBody, out string contentType) { try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_SPARKPOSTURL); webRequest.KeepAlive = false; webRequest.ServicePoint.ConnectionLimit = 24; webRequest.Headers.Add("UserAgent", "MyUserAgent"); webRequest.ProtocolVersion = HttpVersion.Version10; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; webRequest.ContentType = "application/json"; webRequest.Accept = "application/json"; webRequest.Headers.Add("Authorization", _sparkPostAuthorizationKey); webRequest.Method = WebRequestMethods.Http.Post; webRequest.ContentLength = jsonBody.Length; using (Stream dataStream = webRequest.GetRequestStream()) { dataStream.Write(jsonBody, 0, jsonBody.Length); } byte[] bytes; using (WebResponse webResponse = webRequest.GetResponse()) { contentType = webResponse.ContentType; using (Stream stream = webResponse.GetResponseStream()) { using (MemoryStream memoryStream = new MemoryStream()) { byte[] buffer = new byte[0x1000]; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, bytesRead); } bytes = memoryStream.ToArray(); } } } return Encoding.UTF8.GetString(bytes); } catch (Exception ex) { throw new Exception("Failed to retrieve data from SparkPost API: " + ex.Message, ex); } } } }
Once the service class is set up, you can send an email by calling the SendEmail
method:
string sparkPostKey = "your-sparkpost-authorization-key"; string contentType; SparkPostService service = new SparkPostService(sparkPostKey); string result = service.SendEmail(CreateJsonBody("my-first-email", "myCampaign", "[email protected]", "Brian", "Pedersen"), out contentType);
SparkPost offers a robust and easy-to-use solution for email sending, with a generous free tier that allows businesses to send up to 100,000 emails per month at no cost. By using templates and the SparkPost API, you can automate email communication and personalize messages with dynamic content.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#