C#: Send a SparkPost Email From a .NET Website or Application

4/26/2016 2:33:46 AM

This will send an email from a .NET app using the SparkPost.com service. It requires a template to be created in your SparkPost account.

Nuget Package: https://www.nuget.org/packages/SparkPost/

*There seems to be an issue with this Nuget Package (1.2.0) that will cause an MVC site to hang if you try to send an email synchronously. To send this successfully from an MVC website, you will need to have an ASYNC action and then call the ASYNC version of the code below (commented out). From a console app or windows service, the code below works async or sync.

//public static async Task<SendMessageResult> SendMessage(string apiKey, string templateId, string toEmails, string toNames, string fromEmail, Dictionary<string, string> replacementValuePairs)
public static SendMessageResult SendMessage(string apiKey, string templateId, string toEmails, string toNames, string fromEmail, Dictionary<string, string> replacementValuePairs)
{
	var result = new SendMessageResult(); //simple class with string Message, bool Success	
	result.Success = true;

	var transmission = new SparkPost.Transmission();
	transmission.Content.TemplateId = templateId;
	transmission.Content.From.Email = fromEmail;                    

	//replacement tags
	foreach (var pair in replacementValuePairs)
	{
		transmission.SubstitutionData[pair.Key] = pair.Value;                                
	}  
				
	string[] toEmailArray = toEmails.Split(new char[] { ',' });
	string[] toNamesArray = toNames.Split(new char[] { ',' });

	for (int x = 0; x < toEmailArray.Length; x++)
	{                
		var newRecipient = new SparkPost.Recipient();
		var newAddress = new SparkPost.Address();
		newAddress.Email = toEmailArray[x];                
		if (toNamesArray.Length >= toEmailArray.Length)
		{
			newAddress.Name = toNamesArray[x];
		}

		newRecipient.Address = newAddress;            
		transmission.Recipients.Add(newRecipient);
	}
	

	var client = new SparkPost.Client(apiKey);
	
	//if calling async use this
	var response = await client.Transmissions.Send(transmission);	
	
	//if not calling async use this
	var response = await client.Transmissions.Send(transmission).Result;	

	result.Message = response.ReasonPhrase;
	
	if (response.StatusCode != System.Net.HttpStatusCode.OK)
	{
		result.Success = false;  
	}

	return result;           
}


//async action on a controller
public async Task<ActionResult> EmailQueue()
{
	...set your values
	
	//send the message
	var result = await SendMessage(apiKey, templateId, toEmails, toNames, fromEmail, replacementValuePairs);

	//maybe redirect home
	return Redirect("/");
}