UserManager.SendEmailAsync挂起

时间:2014-05-30 12:20:09

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

我有一个带有自定义EmailService的自定义用户管理器。我在AccountController中调用UserManager.SendEmailAsync()方法,它只是挂起。我甚至尝试使用无效的SMTP主机名,然后发生异常,在调试中我可以看到它进入catch块,但无论返回View(模型)语句,它只是"挂起"在浏览器中继续加载。

有什么想法吗?

ApplicationUserManager构造函数:

public ApplicationUserManager(IUserStore<ApplicationUser> store)
    : base(store)
{
    EmailService = new EmailService();
}

EmailService:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Credentials:
        string smtpServer = ConfigurationManager.AppSettings["EmailSmtpServer"];
        int smtpPort = int.Parse(ConfigurationManager.AppSettings["EmailSmtpPort"]);
        bool enableSsl = bool.Parse(ConfigurationManager.AppSettings["EmailEnableSSL"]);
        string smtpUsername = ConfigurationManager.AppSettings["EmailSmtpUsername"];
        string smtpPassword = ConfigurationManager.AppSettings["EmailSmtpPassword"];
        string sentFrom = ConfigurationManager.AppSettings["EmailSentFrom"];

        // Configure the client:
        var client = new SmtpClient(smtpServer, Convert.ToInt32(587));

        client.Port = smtpPort;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.EnableSsl = enableSsl;

        // Create the credentials:
        var credentials = new NetworkCredential(smtpUsername, smtpPassword);
        client.Credentials = credentials;

        // Create the message:
        var mail = new System.Net.Mail.MailMessage(sentFrom, message.Destination);

        mail.Subject = message.Subject;
        mail.Body = message.Body;

        // Send:
        await client.SendMailAsync(mail);
    }
}

AccountController中的ForgotPassword方法

    //
    // POST: /Account/ForgotPassword
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByNameAsync(model.Email);
            // Don't check confirmation status for now
            //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            if (user == null)
            {
                ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
                return View();
            }

            // 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);
            try
            {
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
            return RedirectToAction("ForgotPasswordConfirmation", "Account");
        }

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

1 个答案:

答案 0 :(得分:6)

这对我有用

ApplicationUserManager构造函数:

public AppUserManager(IUserStore<AppUser> store)
        : base(store)
{
        this.UserTokenProvider = new TotpSecurityStampBasedTokenProvider<AppUser, string>();
        this.EmailService = new EmailService();
}

<强> EmailService:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Credentials:
        var credentialUserName = ConfigurationManager.AppSettings["emailFrom"];
        var sentFrom = ConfigurationManager.AppSettings["emailFrom"];
        var pwd = ConfigurationManager.AppSettings["emailPassword"];

        // Configure the client:
        System.Net.Mail.SmtpClient client =
            new System.Net.Mail.SmtpClient("smtp-mail.outlook.com");

        client.Port = 587;
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;

        // Create the credentials:
        System.Net.NetworkCredential credentials =
            new System.Net.NetworkCredential(credentialUserName, pwd);

        client.EnableSsl = true;
        client.Credentials = credentials;

        // Create the message:
        var mail =
            new System.Net.Mail.MailMessage(sentFrom, message.Destination);

        mail.Subject = message.Subject;
        mail.Body = message.Body;

        // Send:
        return client.SendMailAsync(mail);
    }
}

重要如果您使用外部邮件提供商,则应修改外部应用程序配置,例如: gmail:Allowing less secure apps to access your account

AccountController中的ForgotPassword方法

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RecoveryPassword(LoginInfoModel 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");
            }

            var 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",
            "Reinicia tu contraseña clicando : <a href=\"" + callbackUrl + "\">aqui</a>");
            return View("ForgotPasswordConfirmation");
        }

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

最后我在邮箱上看到了我的电子邮件

Mailbox