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

那年仲夏 提交于 2019-12-03 05:40:07

My Email

Hello -REP-

<%body%>

Fotter

My C# Code

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

Works PERFECT!!!

Jimbo Jones

I found the solution:

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

myMessage.AddSubstitution(replacementKey, substitutionValues);

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(
"noreply@example.com", 
"TO_ADDRESS", 
"THE SUBJECT", 
new Dictionary<string, string> { 
{ "@Param1!", "Parameter 1" }, 
{ "@Param2!", "Parameter 2" } }, 
"TEMPLATE_GUID");

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

            SendGridMessage myMessage = new SendGridMessage();
            myMessage.AddTo(email);
            myMessage.AddBcc("MyEmail@gmail.com");
            myMessage.AddBcc("EmailSender_CC@outlook.com");
            myMessage.From = new MailAddress("SenderEmail@outlook.com", "DriverPickup");
            //myMessage.Subject = "Email Template Test 15.";
            myMessage.Headers.Add("X-SMTPAPI", GetMessageHeaderForWelcome("MyEmail@Gmail.com", 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}}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!