Search code examples
c#emailtwiliosendgridsendgrid-templates

How do I send a Sendgrid email using a template and add custom data for the template?


I can send a simple email, I can also send emails using a specific template w/ the TemplateId like the example below, but

QUESTION - How do I send this template below and add or include handlebar data (ex. {"name":"Mike", "url":"some_url", "date":"04/18/2022})?

FYI - I can't find any doc that shows any C# examples. I did find this link to create a transactional template but it doesn't send the email. So not sure here if this is what I'm looking for...

var client = new SendGridClient(Options.SendGridKey);
var msg = new SendGridMessage() {
  From = new EmailAddress(fromEmailAddress, fromEmailName),
  Subject = subject,
  PlainTextContent = message,
  HtmlContent = message,
  TemplateId = "d-30710e173a174ab58cc641nek3c980d4c"
};

var response = await client.SendEmailAsync(msg);


Solution

  • The solution is that you need to remove the PlainTextContent and HtmlContent properties to make use of the template. Also, you need to provide a dynamicTemplateData object that contains your placeholders.

    Here are two code examples that send dynamic template emails with and without the helper class (search for dynamic_template_data and dynamicTemplateData). So the full snippet with the mail helper class would be:

    var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
    var client = new SendGridClient(apiKey);
    var msg = new SendGridMessage();
    msg.SetFrom(new EmailAddress("[email protected]", "Example User"));
    msg.AddTo(new EmailAddress("[email protected]", "Example User"));
    msg.SetTemplateId("d-d42b0eea09964d1ab957c18986c01828");
    
    var dynamicTemplateData = new ExampleTemplateData
    {
        Subject = "Hi!",
        Name = "Example User",
        Location = new Location
            {
            City = "Birmingham",
            Country = "United Kingdom"
            }
        };
    
    msg.SetTemplateData(dynamicTemplateData);
    var response = await client.SendEmailAsync(msg);
    

    PS: Here is the general API documentation that explains the available properties.