0

There is a pre-defined marketing template, and the relevant part of the template looks like this:

Hi [%first_name | Dear Fan%], xxxxxx

There are so many different syntax for sendgrid template variable substitution out there, it's just very confusing. For example, I've seen [%variable_name%], {{variable_name}}, -variable_name- and <%variable_name%>

how do I pass substitution/personalization/template data (just to list the different names I've seen that appears to refer to the same thing) from the C# client to the template?

Andrey Stukalin
  • 5,328
  • 2
  • 31
  • 50
Allen Zhang
  • 2,432
  • 2
  • 20
  • 31

1 Answers1

5

I am assuming you use the official SendGrid Nuget package. In that case you could use the MailHelper class and its methods CreateSingleTemplateEmail, CreateSingleTemplateEmailToMultipleRecipients or CreateMultipleTemplateEmailsToMultipleRecipients depending on your needs. In the simplest case it should be something like this.

            var client = new SendGridClient(ApiKey);

            var dynamicTemplateData = new Dictionary<string, string>
            {
                {"first_name", "John"},
                {"last_name", "Snow"},
            };

            var msg = MailHelper.CreateSingleTemplateEmail(
                new EmailAddress("from@test.com"),
                new EmailAddress("to@test.com"),
                "d-template-id",
                dynamicTemplateData);


            var response = await client.SendEmailAsync(msg);

The above method works surely for transactional templates and I am not 100% sure about marketing ones.

Andrey Stukalin
  • 5,328
  • 2
  • 31
  • 50
  • Here is the unit test from the sendgrid official repo that shows how to use this. https://github.com/sendgrid/sendgrid-csharp/blob/e66855a48e17c99fb8c7b06b58e96c62525fc303/tests/SendGrid.Tests/Helpers/Mail/MailHelperTests.cs#L22-L41= – Ssh Quack May 07 '22 at 23:05