Friday, 9 September 2016

Asp.net MVC: Implement Forgot Password (Password Recovery) and send password in Email in MVC5 & MVC6

9/09/2016 - By Pranav Singh 0

This article will show you how you can implement forgot password (password recovery) and send password in email in mvc5 & mvc6 using c#.net.


So for this article first we will create a new asp.net mvc application and add a controller class file in it. After that create the view and add the below code into the view.

@{
    ViewBag.Title = "Asp.net MVC: Implement Forgot Password (Password Recovery) and send password in Email in MVC5 & MVC6";
}
<script>
    function Validate() {
        var data = document.getElementById("txtEmailID").value;
        if (data == "") {
            alert("Please enter your email id.");
            return false;
        } else {
            return true;
        }
    }
</script>
@using (Html.BeginForm("Index", "Forgotpassword"))
{
    <div>
        Forgot Password:@Html.TextBox("EmailId", "", new { @style = "width:200px;", @id = "txtEmailID" })
        <input type="submit" value="Submit" onclick="javascript: return Validate();" /><br />
        @if (ViewBag.Message == 1)
        {
            <span style="color:green;">Please check your email for account login detail.</span>
        }
        else if (ViewBag.Message == 0)
        {
            <span style="color:red;">Please provide a valid register email id.</span>
        }
    </div>
}

In above code I have added textbox control and a input Sutton control to create the form. This form will request for user email id. In above I have also applied and javascript validation to validate weather user have provided any input or not. Now in above code textbox control name is important. By this name we will be able to access the provided email id at controller end on postback. After this lets check the controller code.

In this first I have created a function which will send the email.

  public string SendPassword(string password, string emailId, string name)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(emailId);
                mail.From = new MailAddress("youremail @gmail.com");
                mail.Subject = "Your password for account " + emailId;
                string userMessage = "";

                userMessage = userMessage + "<br/><b>Login Id:</b> " + emailId;
                userMessage = userMessage + "<br/><b>Passsword: </b>" + password;

                string Body = "Dear " + name + ", <br/><br/>Login detail for your account is a follows:<br/></br> " + userMessage + "<br/><br/>Thanks";
                mail.Body = Body;
                mail.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential("youremail@gmail.com", "password");
                // Smtp Email ID and Password For authentication
                smtp.EnableSsl = true;
                smtp.Send(mail);
                return "Please check your email for account login detail.";
            }
            catch
            {
                return "Error............";
            }
        }

Now check the httpget and post method.

[HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string EmailId)
        {
            /*Create instance of entity model*/
            NorthwindEntities objentity = new NorthwindEntities();
            /*Getting data from database for email validation*/
            var _objuserdetail = (from data in objentity.UserDetails
                                  where data.EmailId == EmailId
                                  select data);
            if (_objuserdetail.Count() > 0)
            {
                string status = SendPassword(_objuserdetail.Password, _objuserdetail.EmailId, _objuserdetail.Name);
                ViewBag.Message = 1;
            }
            else
            {
                ViewBag.Message = 0;
            }
            return View();
        }
In above code I have validated the user from data  base table using entity framework. If we get user detail on that case we will send the tail on the user email otherwise we will throw error message.
Now check the complete code of controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication8.Controllers
{
    public class ForgotpasswordController : Controller
    {
        //
        // GET: /Forgotpassword/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string EmailId)
        {
            /*Create instance of entity model*/
            NorthwindEntities objentity = new NorthwindEntities();
            /*Getting data from database for email validation*/
            var _objuserdetail = (from data in objentity.UserDetails
                                  where data.EmailId == EmailId
                                  select data);
            if (_objuserdetail.Count() > 0)
            {
                string status = SendPassword(_objuserdetail.Password, _objuserdetail.EmailId, _objuserdetail.Name);
                ViewBag.Message = 1;
            }
            else
            {
                ViewBag.Message = 0;
            }
            return View();
        }
        public string SendPassword(string password, string emailId, string name)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(emailId);
                mail.From = new MailAddress("youremail @gmail.com");
                mail.Subject = "Your password for account " + emailId;
                string userMessage = "";

                userMessage = userMessage + "<br/><b>Login Id:</b> " + emailId;
                userMessage = userMessage + "<br/><b>Passsword: </b>" + password;

                string Body = "Dear " + name + ", <br/><br/>Login detail for your account is a follows:<br/></br> " + userMessage + "<br/><br/>Thanks";
                mail.Body = Body;
                mail.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential("youremail@gmail.com", "password");
                // Smtp Email ID and Password For authentication
                smtp.EnableSsl = true;
                smtp.Send(mail);
                return "Please check your email for account login detail.";
            }
            catch
            {
                return "Error............";
            }
        }
    }
}


Now we have done run the application to check the output. First add an invalid email id.

Now provide a valid email id.


Now lets check the email .


  Please let me know you comment.

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top