Search code examples
c#sendgridsendgrid-templates

C# client how to pass subsititution variables to sendgrid marketing template?


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?


Solution

  • 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("[email protected]"),
                    new EmailAddress("[email protected]"),
                    "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.