How to Add Custom variables to SendGrid email via API C# and Template

Jimbo Jones picture Jimbo Jones · Sep 17, 2014 · Viewed 12k times · Source

I am trying to figure out how to add variables to existing template (example: Web Link Or Name dynamically) which has been created in sendgrid template engine, I am unsure how to do this using the SendGrid C# .NET libraries. I am wondering if anyone could help me.

// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();

myMessage.AddTo("[email protected]");
myMessage.From = new MailAddress("[email protected]", "Mr test");
myMessage.Subject = " ";

var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
myMessage.Html = "<p></p> ";

myMessage.EnableTemplate("<p> <% body %> Hello</p>");
myMessage.EnableTemplateEngine("9386b483-8ad4-48c2-9ee3-afc7618eb56a");
var identifiers = new Dictionary<String, String>();
identifiers["USER_FULLNAME"] = "Jimbo Jones";
identifiers["VERIFICATION_URL"] = "www.google.com";
myMessage.AddUniqueArgs(identifiers);

// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("username", "password");
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
transportWeb.Deliver(myMessage);

Answer

Oswaldo Alvarez picture Oswaldo Alvarez · Oct 21, 2014

My Email

Hello -REP-

<%body%>

Fotter

My C# Code

myMessage.AddSubstitution("-REP-", substitutionValues);

Works PERFECT!!!