0

I am having this code to send e-mail to reset user password:

//
        // POST: /Account/ForgotPassword
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> ForgotPassword(ForgotPasswordViewModel model, bool CaptchaValid)
        {
            string mensaje = String.Empty;

            if (ModelState.IsValid)
            {
                if (!CaptchaValid)
                    mensaje = "ERROR: Captcha inválido.";
                else
                {
                    var user = await UserManager.FindByEmailAsync(model.Email);
                    if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                    {
                        mensaje = "ERROR: La dirección de correo electrónico no está registrada.";
                    }
                    else
                    {
                        var provider = new DpapiDataProtectionProvider("WebAttendance");
                        UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, string>(provider.Create("UserToken")) as IUserTokenProvider<ApplicationUser, string>;
                        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", "Por favor, cambie su contraseña al hacer click <a href=\"" + callbackUrl + "\">aquí</a>");
                        return Json("INFO: Se envió un mail a su cuenta de correo con instrucciones para cambiar su contraseña.");
                    }
                }
            }

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

The above code runs without any error, but e-mail is not actually sent.

This is the Web.config entries:

  <system.net>
    <mailSettings>
      <smtp from="info@xxx.com">
        <network host="mail.desytec.cl" password="xxxx" port="587" userName="yyy@xxx.cl"  enableSsl="false"/>
      </smtp>
    </mailSettings>
  </system.net>

By the way, when reading some posts, I knew that I have to have IdentityConfig.cs file in App_Start, but that file is missing. May this be the cause?

jstuardo
  • 3,901
  • 14
  • 61
  • 136
  • Where in the code are you sending an email ? where did you initialize smtp and use smtp configuration to send email ? – ISHIDA Jun 22 '17 at 01:31
  • https://stackoverflow.com/questions/40674457/how-to-configure-sender-email-credentials-for-asp-net-identity-usermanager-sende – Yuri S Jun 22 '17 at 01:47
  • I think this is done automatically by UserManager.SendEmailAsync call – jstuardo Jun 22 '17 at 02:03
  • @YuriS I have read that before. See what I wrote regarding IdentityConfig.cs. However, I have added that file manually with the code shown in that post, but it did not work. – jstuardo Jun 22 '17 at 02:08
  • if you don't have that file that means you didn't create that project properly. It is not enough just add it. There are some code settings things up. For example in public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) should be call var manager = new ApplicationUserManager(new UserStore(context.Get())); then manager.EmailService = new EmailService(); I would recreate the project properly – Yuri S Jun 22 '17 at 16:00
  • @YuriS what do you mean by "properly"? I use Visual Studio 2012. I have just created a MVC5 project. No special options I could choose. Well... I have this in AccountController constructor: UserManager = new UserManager(new UserStore(db)); Can I instantiate EmailService there? – jstuardo Jun 26 '17 at 02:31
  • Using correct wizard. Unfortunately I cannot help you because I am not using 2012 long time already. May be you are trying to use recent samples with VS2012. That might not work. – Yuri S Jun 26 '17 at 03:42
  • But how to do it without wizard? The project is created already. If you have a more recent VS, can you please show me the code it generates in order to send the e-mail successfully? – jstuardo Jun 26 '17 at 13:33

1 Answers1

0

You probably already got your answer, but this was the first post that Google showed me, so I'm answering it for completeness.

Look inside your IdentityConfig.cs file in the App_Start folder. You should find code similar to:

public class EmailService : IIdentityMessageService {
    public Task SendAsync(IdentityMessage message) {
        // Plug in your email service here to send an email.
        return Task.FromResult(0);
    }
}

I misunderstood several other posts and thought I had to created a new class with the code above. Instead, you'll need to update this method to send the email with whatever email service you want to use.

I ended up with something similar, but not exact to this, so you'll have to test if this truly works for you.

// code from https://stackoverflow.com/questions/40674457/how-to-configure-sender-email-credentials-for-asp-net-identity-usermanager-sende
public async Task SendAsync(IdentityMessage message) {
    // Plug in your email service here to send an email.
    SmtpClient client = new SmtpClient();
    await client.SendMailAsync("email from web.config here",
                                message.Destination,
                                message.Subject,
                                message.Body);
}
RoLYroLLs
  • 3,113
  • 4
  • 38
  • 57