Search code examples
c#sendgrid

Asp.net Core SendGrid Dynamic Template Integration


I recently added SendGrid to my .net Core razor project. In order to make the automated account confirmation and password reset emails more professional I've tried to implement the dynamic templates. Email was working fine before, but as soon as I added the Template ID using the SendGrid helper, the emails won't send.

 //string emailString = "<html><body>"
                    //+ "<img src='https://publishendersapp.azwebsites.net/images/logo.png' />"
                    //+ "<p>Dear " + user.FirstName + ",</p>"
                    //    + "<p>Thank you for registering for PublishFinders.com! We are glad to have you on board.</p>"
                    //    + $"Please <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'> click </a> here to confirm your email address. <br />"


                    //    + "<p>Thank you for registering ! </p>"
                    //    + "<p>The PublisherFinders Team</p>" +
                    //    "</body></html>";

                    //await _emailSender.SendEmailAsync(
                    //    Input.Email, "Confirm your email ", emailString

                    //    );

This code use it's working fine but not working send with Template


Solution

  • The following works for me fine:

    var templateId = "x-xxxxxxxxxx";
    var dynamicTemplateData = new { };
    
    // Create a SendGrid E-Mail
    var apiKey = _config.GetValue<string>("SendGridKey");
    var emailKey = _config.GetValue<string>("Email");
    var client = new SendGridClient(apiKey);
    EmailAddress feedbackFrom =  new EmailAddress(emailKey, null);
    
    var feedBack = MailHelper.CreateSingleTemplateEmail(feedbackFrom, feedBackTo, templateId, dynamicTemplateData);
    var feedBackResponse = await client.SendEmailAsync(feedBack);
    

    That's all!