I recently added SendGrid to my ASP.net Core 2.2 MVC 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. When I remove the template ID, everything works fine again. I've sent the JSON snippet (i think that's what it's called?) to SendGrid support and they said it runs fine on their end, so something is stopping it from executing in the program. I've tried adding and removing subject and content in case it didn't like that, but that didn't change anything. My code is below. Thank you so much for any help or ideas to try.
public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string message);
}
public Task SendEmailAsync(string email, string subject, string message)
{
return Execute(Options.SendGridKey, email);
}
public Task Execute(string apiKey, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("FROM EMAIL ADDRESS", "SENDER NAME"),
Subject = "testtest",
PlainTextContent = "test1",
HtmlContent = "test2"
};
msg.AddTo(new EmailAddress(email));
// removing the msg.SetTemplateId line allows email to start working again. Adding it back in breaks it.
msg.SetTemplateId("MY TEMPLATE ID");
// Disable click tracking.
// See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
msg.SetClickTracking(false, false);
var debug = (msg.Serialize());
return client.SendEmailAsync(msg);
}
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "EMAIL SUBJECT",
$"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}