MVC ForgotPassword方法不发送重置电子邮件

时间:2017-05-15 08:52:56

标签: c# asp.net asp.net-mvc

我的AccountController中有以下GET和POST方法:

// GET: /Account/ForgotPassword
        [AllowAnonymous]
        public ActionResult ForgotPassword()
        {
            return View();
        }

        //
        // POST: /Account/ForgotPassword
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // 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.GeneratePasswordResetTokenAsync(user.Id);
                 var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);     
                 await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

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

这使用Visual Studio定义的标准ForgotPassword方法。我只是在我的登录页面上放了一个actionlink,如下所示:

                <p>
                    @Html.ActionLink("Forgot your password?", "ForgotPassword")
                </p>

问题是,在ForgotPassword视图中提交要重置的电子邮件后,我没有收到注册用户的重置电子邮件。我的代码有什么问题吗?

我还在我的Web.config中配置了这样的邮件设置,所以这应该不是问题所在:

 <mailSettings>
  <smtp from="MyEmail">
    <network host="smtp.gmail.com" port="587" userName="MyEmail" password="MyEmailPassword" enableSsl="true" />

  </smtp>
</mailSettings>

我在Stackoverflow上尝试过类似问题的答案,如更改行:

 await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

但那没用。我还允许低安全性应用程序向我的帐户发送电子邮件。我也尝试在我的smtp标签下设置deliveryMethod="Network",但这也无济于事。

没有收到重置电子邮件可能会出现什么问题?

1 个答案:

答案 0 :(得分:2)

在您访问低安全应用并启用电子邮件转发协议之前,Gmail smtp不会发送电子邮件。

启用电子邮件转发(POP)后,您应该收到来自Google的电子邮件,说有人试图发送邮件等邮件,并通过邮件启用低安全应用程序以通过Gmail发送电子邮件。