2/9/2015 4:16:44 PM

Mandrill is MailChimp's transactional email service. This code will allow you to send an email using Mandrill. You will need a Mandrill account, a Mandrill Outbound template, and an API key.

* Requires Newtonsoft JSON Nuget Package (or referenced dll).

//url to send data to string apiUrl = "https://mandrillapp.com/api/1.0/messages/send-template.json"; //account api key needed to send email //created at: https://mandrillapp.com/settings string mandrillKey = "my-secret-api-key"; //name of the email template created in mandrill string mandrillTemplateId = "my-test-01"; //list of emails to send the email to List<string> toEmails = new List<string>(); toEmails.Add("user@example.com"); //list of to names for emails above List<string> toNames = new List<string>(); toNames.Add("Mr. Example"); //replacement values to add to the email //these replacement tags must be added to your Mandrill tempalte: ex: <a href="*|site_url|*">Site Url</a> List<KeyValuePair<string, string>> replacementValues = new List<KeyValuePair<string, string>>(); replacementValues.Add(new KeyValuePair<string, string>("site_url", "http://www.example.com")); dynamic sendParams = new System.Dynamic.ExpandoObject(); sendParams.key = mandrillKey; sendParams.template_name = mandrillTemplateId; sendParams.template_content = new List<dynamic>(); sendParams.message = new System.Dynamic.ExpandoObject(); sendParams.message.to = new List<dynamic>(); //to emails for (int x = 0; x < toEmails.Count; x++) { sendParams.message.to.Add(new System.Dynamic.ExpandoObject()); sendParams.message.to[x].email = toEmails[x]; } //to names - in same order as to emails for (int x = 0; x < toNames.Count; x++) { //dont add if email wasnt added if (toEmails.Count >= x + 1) { sendParams.message.to[x].name = toNames[x]; } } //additional mandrill options sendParams.message.track_opens = true; //sendParams.message.track_clicks = true; //create replacement values object to merge in sendParams.message.global_merge_vars = new List<dynamic>(); int counter = 0; foreach (var pair in replacementValues) { sendParams.message.global_merge_vars.Add(new System.Dynamic.ExpandoObject()); sendParams.message.global_merge_vars[counter].name = pair.Key; sendParams.message.global_merge_vars[counter].content = pair.Value; counter++; } //json send parameters string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(sendParams); //create web client to post data var request = new System.Net.WebClient(); //set content type to json since we are posting json data request.Headers[HttpRequestHeader.ContentType] = "application/json"; //post json data and get the response string responseString = request.UploadString(apiUrl, jsonString); //read the results bool success = false; if (!string.IsNullOrWhiteSpace(responseString)) { dynamic resultObj = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString); if (resultObj != null) { if (resultObj[0] != null) { if (resultObj[0].status == "sent") { success = true; } } } }