Jimbo Jones
Jimbo Jones

Reputation: 1002

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

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);

Upvotes: 13

Views: 14579

Answers (4)

Jimbo Jones
Jimbo Jones

Reputation: 1002

I found the solution:

replacementKey = "*|VERIFICATION_URL|*";
substitutionValues = new List<string> { VERIFICATION_URL };

myMessage.AddSubstitution(replacementKey, substitutionValues);

Upvotes: 6

Optimus
Optimus

Reputation: 575

After did lots of RND. My below code is working fine & Tested as well.

            SendGridMessage myMessage = new SendGridMessage();
            myMessage.AddTo(email);
            myMessage.AddBcc("[email protected]");
            myMessage.AddBcc("[email protected]");
            myMessage.From = new MailAddress("[email protected]", "DriverPickup");
            //myMessage.Subject = "Email Template Test 15.";
            myMessage.Headers.Add("X-SMTPAPI", GetMessageHeaderForWelcome("[email protected]", callBackUrl));
            myMessage.Html = string.Format(" ");

            // Create an Web transport for sending email.
            var transportWeb = new Web(SendGridApiKey);

            // Send the email, which returns an awaitable task.
            transportWeb.DeliverAsync(myMessage);

I have created Separate method for getting JSON header

private static string GetMessageHeaderForWelcome(string email, string callBackUrl)
    {

        var header = new Header();
        //header.AddSubstitution("{{FirstName}}", new List<string> { "Dilip" });
        //header.AddSubstitution("{{LastName}}", new List<string> { "Nikam" });
        header.AddSubstitution("{{EmailID}}", new List<string> { email });
        header.AddSubstitution("-VERIFICATIONURL-", new List<string>() { callBackUrl });
        //header.AddSubstitution("*|VERIFICATIONURL|*", new List<string> { callBackUrl });
        //header.AddSubstitution("{{VERIFICATIONURL}}", new List<string> { callBackUrl });
        header.AddFilterSetting("templates", new List<string> { "enabled" }, "1");
        header.AddFilterSetting("templates", new List<string> { "template_id" }, WelcomeSendGridTemplateID);
        return header.JsonString();

    }

Below code I have used in my HTML Sendgrid template.

<div>Your {{EmailID}} register. Please <a class="btn-primary" href="-VERIFICATIONURL-">Confirm email address</a></div>

In case if any query please let me know.

For inline HTML replace you need to use -YourKeyForReplace- & for text replace you need to use {{UserKeyForReplace}}

Upvotes: 3

Josh Jennings
Josh Jennings

Reputation: 39

I've used the following approach. Note you have to provide the mail.Text and mail.Html values - I use the empty string and <p></p> tag as seen in the example. Your SendGrid template also still must contain the default <%body%> and <%subject%> tokens, although they will be replaced with the actual subject and body value specified in the mail.Text and mail.Html properties.

public void Send(string from, string to, string subject, IDictionary<string, string> replacementTokens, string templateId)
{
  var mail = new SendGridMessage
  {
    From = new MailAddress(from)
  };

  mail.AddTo(to);
  mail.Subject = subject;

  // NOTE: Text/Html and EnableTemplate HTML are not really used if a TemplateId is specified
  mail.Text = string.Empty;
  mail.Html = "<p></p>";
  mail.EnableTemplate("<%body%>");

  mail.EnableTemplateEngine(templateId);

  // Add each replacement token
  foreach (var key in replacementTokens.Keys)
  {
    mail.AddSubstitution(
      key,
      new List<string>
        {
          replacementTokens[key]
        });
  }

  var transportWeb = new Web("THE_AUTH_KEY");
  var result = transportWeb.DeliverAsync(mail);
}

It can then be called like this:

Send(
"[email protected]", 
"TO_ADDRESS", 
"THE SUBJECT", 
new Dictionary<string, string> { 
{ "@Param1!", "Parameter 1" }, 
{ "@Param2!", "Parameter 2" } }, 
"TEMPLATE_GUID");

Upvotes: 3

Oswaldo Alvarez
Oswaldo Alvarez

Reputation: 4812

My Email

Hello -REP-

<%body%>

Fotter

My C# Code

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

Works PERFECT!!!

Upvotes: 10

Related Questions