【问题标题】:SendGrid is not sending an emailSendGrid 没有发送电子邮件
【发布时间】:2016-08-16 14:33:35
【问题描述】:

我一直在关注本教程:http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset。我现在已经浏览了三遍,并检查了几个 Stackoverflow 帖子,但我仍然不知道我错过了什么。通过调试 Visual Studio 显示 myMessage 具有它需要的所有内容(要发送到的电子邮件地址、消息主题、消息正文、来自谁等),但我在测试它时实际上并没有收到确认电子邮件。这是我目前拥有的代码:

IdentityConfig.cs

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        // line below was commented out and replaced upon tutorial request
        //return Task.FromResult(0);
        await configSendGridasync(message);
    }
    // Use NuGet to install SendGrid (Basic C# client lib) 
    private async Task configSendGridasync(IdentityMessage message)
    {
        var myMessage = new SendGridMessage();
        myMessage.AddTo(message.Destination);
        myMessage.From = new System.Net.Mail.MailAddress(
                            "myActualEmail@email.com", "Robert");
        myMessage.Subject = message.Subject;
        myMessage.Text = message.Body;
        myMessage.Html = message.Body;

        var credentials = new NetworkCredential(
                   ConfigurationManager.AppSettings["mailAccount"],
                   ConfigurationManager.AppSettings["mailPassword"]
                   );

        // Create a Web transport for sending email.
        var transportWeb = new Web(credentials);

        // Send the email.
        if (transportWeb != null)
        {
            await transportWeb.DeliverAsync(myMessage);
        }
        else
        {
            Trace.TraceError("Failed to create Web transport.");
            await Task.FromResult(0);
        }
    }
}

帐户控制器:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // commented below code and RedirectToAction out so it didn't auto log you in.
                //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                //For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                //Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                ViewBag.Message = "Check your email and confirm your account, you must be confirmed before you can log in.";

                return View("Info");

                //return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Web.config:

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />

    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="mailAccount" value="azure_d8aedad6a68a0dc1dc8axxxxxxxxxxxx@azure.com" /> <!--the mailAccount that SendGrid gave me through Azure marketplace to use-->
    <add key="mailPassword" value="xxxxxx" /> <!--password taken out, but I used the one from SendGrid-->
</appSettings>

代码构建和运行没有错误,但我在测试时从未收到实际的电子邮件(我使用了两个单独的 gmail 帐户和一个 yahoo 帐户)。任何建议/帮助将不胜感激!

【问题讨论】:

  • 我在从本地开发机器发送 sendgrid 时遇到了问题,但是一旦我将它部署到服务器/主机,它就会按预期工作。 (为了它的价值)
  • 不是 100% 确定 SendGrid 端可以使用什么,但看起来有某种仪表板。有什么迹象吗?
  • @GlennFerrie 我想我现在可以尝试部署看看,但在我这样做之前我想要更多的成品。我从 Azure 网站上查看了 SendGrid 的信息,并没有真正找到任何东西。我会多看一点。感谢您的建议!
  • @RobertPrine - 在与 SendGrid 集成时,我使用 .NET 类型、SmtpClient 和 MailMessage 的运气更好。您将使用 sendgrid smtp 主机和您的 sendgrid 凭据,并确保使用端口 587。这里有更多信息:sendgrid.com/docs/Integrate/index.html
  • 您的 ISP 或本地防火墙可能会阻止出站流量。

标签: c# razor sendgrid


【解决方案1】:

看来您可以像这样在 web.config 文件中使用 &lt;system.net&gt; &lt;mailSettings&gt; &lt;smpt&gt; 配置的 dotNet MailMessageSmtpClient

发送:

    var mailMessage = new MailMessage(...);
    var smtpClient = new SmtpClient();
    smtpClient.Send(message);

.config 中的 SendGrid 配置:

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network" from="MYFROM@example.com">
            <network host="smtp.sendgrid.net" password="PASS`"
                     userName="YOURNAME_AZURE_SENDGRID_USERNAME@azure.com" port="587" />
        </smtp>
    </mailSettings>
</system.net>

【讨论】:

  • 感谢@Artyom 的建议回答!我对 Visual Studio MVC 比较陌生,并且无法找到将建议的更改放在哪里。我假设我会在 web.config 中添加 .config 信息而不是我的 ,但我无法确定将“发送”部分放在哪里。我假设它将替换大部分 IdentityConfig.cs,但是当我尝试切换时遇到很多构建错误。如果您可以提供有关如何将我当前的代码与您的代码结合起来的任何其他细节,我将非常感激。再次感谢!
  • 是的,&lt;system.net&gt; 将被放入&lt;configuration&gt; 下的 web.config 中。 “发送”代码,SmtpClient(更多示例参见msdn)将进入您的UserManager.SendEmailAsync 方法。希望能帮助到你!请不要忘记为答案投票。
猜你喜欢
  • 2017-12-26
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 2018-11-08
  • 1970-01-01
相关资源
最近更新 更多