我最近将 SendGrid 添加到我的 ASP.net Core 2.2 MVC 项目中。为了使自动帐户确认和密码重置电子邮件更专业,我尝试实施动态模板。电子邮件以前工作正常,但是一旦我使用 SendGrid 帮助程序添加模板 ID,电子邮件就不会发送。当我删除模板 ID 时,一切正常。我已经将 JSON 片段(我认为这就是它的名称?)发送给 SendGrid 支持,他们说它在他们的末端运行良好,所以有些东西阻止它在程序中执行。我已经尝试添加和删除主题和内容,以防万一它不喜欢那样,但这并没有改变任何东西。我的代码如下。非常感谢您提供任何帮助或尝试的想法。
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);
}