Thursday, 3 November 2016

// // Leave a Comment

How to send forgot password link on email for reset in asp.net C#

How to send a reset password link on the mail. We need maximum time to use the code in our project so I have designed this .In this post I  have sending the mail using the Gmail, if you want to send with another domain then you can change the smtp and port number. In this first we check the email is available in data base or not then we send a link on that email. Using that we can change/update our password.

Script the creating table:-

create database [CodeSolution]

USE [CodeSolution]
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[logintable](
          [uid] [int] IDENTITY(1,1) NOT NULL,
          [email] [nvarchar](50) NULL,
          [password] [nvarchar](50) NULL,
          [password_change_status] [bit] NULL,
 CONSTRAINT [PK_logintable] PRIMARY KEY CLUSTERED
(
          [uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  =OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON,ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Source code (forgotpasswordemail.aspx)

<%@ Page Language="C#" AutoEventWireup="true"CodeFile="forgotpasswordemail.aspx.cs"Inherits="forgotpasswordemail" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table align="center">
        <tr><td>Email:</td><td>
        <asp:TextBox ID="txtemail" runat="server" Width="150px"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvemail" runat="server"

                ErrorMessage="Please Enter Email"ControlToValidate="txtemail"

                ForeColor="Red"></asp:RequiredFieldValidator>

            </td></tr>

        <tr><td>&nbsp;</td><td>

            <asp:Button ID="btnsend" runat="server" Text="Send"onclick="btnsend_Click" /></td></tr>

        <tr><td colspan="2">
            <asp:Label ID="lbresult" runat="server"></asp:Label>
            </td></tr>

        </table>
    </div>
    </form>
</body>
</html>

Code behind (forgotpasswordemail.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.Data;

public partial class forgotpasswordemail : System.Web.UI.Page
{

    SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa;Password=12345678");

    DataTable dt = new DataTable();
    protected void page_Load(object sender, EventArgs e)
    {
   
   
    }
    protected void btnsend_Click(object sender, EventArgs e)
    {

        try
        {

            Session["email"] = txtemail.Text;

            SqlDataAdapter adp = new SqlDataAdapter("select * from logintable where email=@email", con);
            con.Open();

            adp.SelectCommand.Parameters.AddWithValue("@email", txtemail.Text);

            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {

                SqlCommand cmd = new SqlCommand("Update logintable set password_change_status=1 where email='" + txtemail.Text + "'", con);

                cmd.ExecuteNonQuery();

                SendEmail();

                lbresult.Text = "successfully sent reset link on  your mail ,please check once! Thank you.";
                con.Close();

                cmd.Dispose();

                txtemail.Text = "";

            }
            else {

                lbresult.Text = "Please enter vaild email ,please check once! Thank you.";
               
            }

        }

        catch (Exception ex)
        {

        }

    }

    // using this method we sent the mail to reciever

    private void SendEmail()
    {

        try
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("Hi,<br/> Click on below given link to Reset Your Password<br/>");
            sb.Append("<a href=http://localhost:57355/codesoluation/resetlink.aspx?username=" + GetUserEmail(txtemail.Text));
            sb.Append("&email=" + txtemail.Text + ">Click here to change your password</a><br/>");
            sb.Append("<b>Thanks</b>,<br> Code Solution <br/>");
            sb.Append("<br/><b> for more post </b> <br/>");
            sb.Append("<br/><a href=http://neerajcodesolution.blogspot.in");
            sb.Append("thanks");

            MailMessage message = newSystem.Net.Mail.MailMessage("neerajsrivastava@gmail.com", txtemail.Text.Trim(), "Reset Your Password", sb.ToString());

            SmtpClient smtp = new SmtpClient();

            smtp.Host = "smtp.gmail.com";

            smtp.Port = 587;

            smtp.Credentials = newSystem.Net.NetworkCredential("neerajsrivastava @gmail.com","987654321");

            smtp.EnableSsl = true;

            message.IsBodyHtml = true;

            smtp.Send(message);

        }

        catch (Exception ex)
        {

        }
    }

    private string GetUserEmail(string Email)
    {
        SqlCommand cmd = new SqlCommand("select email from logintable WHERE email=@email", con);
        cmd.Parameters.AddWithValue("@email", txtemail.Text);
        string username = cmd.ExecuteScalar().ToString();
        return username;
    }
}


Source code (resetlink.aspx)

<%@ Page Language="C#" AutoEventWireup="true"CodeFile="resetlink.aspx.cs" Inherits="resetlink" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width44%;
        }
        .style2
        {
            width128px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        <table class="style1" align="center">
            <tr>
                <td class="style2">
                    New Password
                </td>
                <td>
                    <asp:TextBox ID="txtpwd" runat="server"Width="158px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Confirm Password
                </td>
                <td>
                    <asp:TextBox ID="txtcofrmpwd" runat="server"Width="158px"></asp:TextBox>
                    <asp:CompareValidator ID="CompareValidatorPassword"runat="server" ControlToCompare="txtpwd"
                        ControlToValidate="txtcofrmpwd"ErrorMessage="Password does not match" Font-Names="Rockwell"
                        ForeColor="Red"></asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;
                </td>
                <td>
                    <asp:Button ID="btnsubmit" runat="server"Text="Submit" Width="156px" OnClick="btnsubmit_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Code behind (resetlink.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class resetlink : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        string email = Session["email"].ToString();
    }

    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        string email = Session["email"].ToString();

        SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa;Password=12345678");
        SqlCommand cmd = new SqlCommand("Update logintable set password = '"+txtpwd.Text+"'where email= '"+email+"'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Response.Write("<script>alert ('your password has been successfully updated')</script>");
        txtpwd.Text = "";
        txtcofrmpwd.Text = "";

    }
}

0 comments:

Post a Comment