Sendgrid with template: email is generated without replaceing template variable using .NET 6

106 Views Asked by At

I have created 2 templates in sendgrid. Each of the template has templates {{{Subject}}} and in the body for {{{Name}}} and some other templated fields.

I have tried multiple ways to generate the email. Emails are being sent with the data in the template however the template variables are not being replaced, instead I am getting the empty value. I am not sure what I am doing wrong.

Please take a look at the code below. In multiple forums, I tried many ways and lastly I came to ask this question.

  //  ----------------------example1------------------------------------

    var from = new EmailAddress("[email protected]");
    var receipent = new EmailAddress( "[email protected]");

    var templateId = id;
    var dynamicTemplateData = new
    {
        Subject = "Template field for subject",
        FailedFirstName = "template Amir",
        FailedMiddleInitial = "template Last Name",
        FormName = " Templae form name",
        FormRemarks = "template remarks"

    };
   
    var d = MailHelper.CreateSingleTemplateEmail(from, receipent, templateId, dynamicTemplateData);

    var response = await client.SendEmailAsync(d);
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("Email has been sent successfully");
    }

    //------------example 1 ended------------------------------//

    ///-----------example 2---------------------------------
    ///
    var msg = new SendGridMessage();
    msg.SetFrom(new EmailAddress("[email protected]"));
    msg.AddTo(new EmailAddress("[email protected]"));
    msg.SetTemplateId(id);

    var dynamicTemplateData2 = new 
    {

        Subject = "Template field for subject",
        FailedFirstName = "template Amir",
        FailedMiddleInitial = "template Last Name",
        FormName = " Templae form name",
        FormRemarks = "template remarks"
    };

    var response2 = await client.SendEmailAsync(msg);

    ///  example 2-----------------------------------//

Template screenshot:

enter image description here

This is the email I received, it's without the template field. In the body there are templated fields are empty:

enter image description here

0

There are 0 best solutions below