0

我最近将 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);
    }
4

1 回答 1

0

电子邮件以前工作正常,但是一旦我使用 SendGrid 帮助程序添加模板 ID,电子邮件就不会发送。当我删除模板 ID 时,一切正常。

我使用以下代码片段与我的 SendGrid 电子邮件服务和现有的动态模板进行了测试,这对我来说效果很好。

您可以使用您的apiKeytemplateID进行测试,请确保您指定的 templateID 有效。

var client = new SendGridClient(apiKey);
var msg = new SendGridMessage();
msg.SetFrom(new EmailAddress("{email_address_here}", "SENDER NAME"));
msg.AddTo(new EmailAddress("{email_address_here}", "RECEIVER NAME"));
msg.SetTemplateId("{templateID_here}"); // templateID look like: d-4f0a1515501a4a9dad5646a8c1xxxxx

var response = await client.SendEmailAsync(msg);

注意:在上面的测试中,安装并使用Sendgrid v9.12.7

于 2020-02-26T08:40:43.203 回答