aspdotnet-suresh offers articles and tutorials,csharp dot net, articles and tutorials,VB.NET Articles,Gridview articles,code examples of 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Code for Forgot Password in using C#, VB.NET with Email

Nov 1, 2012

In this article I will explain how to write code to recover forgot password in using c# and


In previous posts I explained Create ContactUs Page in,
send mail using gmail account in, send mail with images using gmail in, send html page as mail body in and many articles on send mail in Now I will explain how to write code to recover forgot password in using c# and

Before implement this first design one table UserInfo in your database like as shown below

Column Name
Data Type
Allow Nulls
int (Set Identity=true)
Once table design complete enter some dummy for our example like as shown below


Now we are going to use our gmail account credentials to send mail for that first you need to enable POP enable option in your Gmail account for that you need to open your gmail account and go to Settings-->Forwarding and POP/IMAP

After that design your aspx page like this

<html xmlns="">
<head id="Head1" runat="server">
<title>Code to recover forgot password in using C# and VB.NET</title>
<style type="text/css">
background-color :#FF5A00;
color: #FFFFFF;
font-weight: bold;
margin-right: 2px;
padding: 4px 20px 4px 21px;
<form id="form1" runat="server">
<table cellspacing="2" cellpadding="2" border="0">
<tr><td></td><td><b>Forgot Password Example</b></td></tr>
<tr><td><b>Enter Your Email:</b></td><td><asp:TextBox ID="txtEmail" runat="server" /></td></tr>
<tr><td></td><td><asp:button ID="btnSubmit" Text="Submit"  runat="server" onclick="btnSubmit_Click" CssClass="Button"/></td></tr>
<tr><td colspan="2" style=" color:red"><asp:Label ID="lbltxt" runat="server"/></td></tr>
After that add following namespaces in your codebehind

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;

After that write the following code in button click

protected void btnSubmit_Click(object sender, EventArgs e)
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
SqlCommand cmd = new SqlCommand("SELECT UserName,Password FROM UserInfo Where Email= '" + txtEmail.Text.Trim() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
MailMessage Msg = new MailMessage();
// Sender e-mail address.
Msg.From = new MailAddress(txtEmail.Text);
// Recipient e-mail address.
Msg.Subject = "Your Password Details";
Msg.Body = "Hi, <br/>Please check your Login Detailss<br/><br/>Your Username: " + ds.Tables[0].Rows[0]["UserName"] + "<br/><br/>Your Password: " + ds.Tables[0].Rows[0]["Password"] + "<br/><br/>";
Msg.IsBodyHtml = true;
// your remote SMTP server IP.
SmtpClient smtp = new SmtpClient();
smtp.Host = "";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential ("", "yourpassword");
smtp.EnableSsl = true;
//Msg = null;
lbltxt.Text = "Your Password Details Sent to your mail";
// Clear the textbox valuess
txtEmail.Text = "";
lbltxt.Text = "The Email you entered not exists.";
catch (Exception ex)
Console.WriteLine("{0} Exception caught.", ex);

Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Dim cmd As New SqlCommand("SELECT UserName,Password FROM UserInfo Where Email= '" & txtEmail.Text.Trim() & "'", con)
Dim da As New SqlDataAdapter(cmd)
End Using
If ds.Tables(0).Rows.Count > 0 Then
Dim Msg As New MailMessage()
' Sender e-mail address.
Msg.From = New MailAddress(txtEmail.Text)
' Recipient e-mail address.
Msg.Subject = "Your Password Details"
Msg.Body = "Hi, <br/>Please check your Login Detailss<br/><br/>Your Username: " & Convert.ToString(ds.Tables(0).Rows(0)("UserName")) & "<br/><br/>Your Password: " & Convert.ToString(ds.Tables(0).Rows(0)("Password")) & "<br/><br/>"
Msg.IsBodyHtml = True
' your remote SMTP server IP.
Dim smtp As New SmtpClient()
smtp.Host = ""
smtp.Port = 587
smtp.Credentials = New System.Net.NetworkCredential ("", "yourpassword")
smtp.EnableSsl = True
'Msg = null;
lbltxt.Text = "Your Password Details Sent to your mail"
' Clear the textbox valuess
txtEmail.Text = ""
lbltxt.Text = "The Email you entered not exists."
End If
Catch ex As Exception
Console.WriteLine("{0} Exception caught.", ex)
End Try
End Sub
End Class
Download Sample code Attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest,, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email


vipin pandey said...

hi Suresh ji! good morning ! You r doing great job.I daily go through with your articles.

Actually sir,right now i m looking for a job change and everybody is asking WCF and MVC in interview.

Please teach us MVC and WCF and make us master in WCF and MVC as in your other articles like gridview,javascript etc..
highly thankful to you.
Vipin Kumar Pandey

vipin pandey said...

your all articles r awesome!!

Tapan said...

Hello suresh sir,

Please add one type of article that How to change Language dynamically in a website.

Chandu said...

nice article suresh ji......

Anonymous said...

thank for provide nice article its very helpful for interview dapfor. com

Abhinavsingh993 said...

Sir, My final B.Tech Final Year Project is "Mailing Website like Gmail" obiviously it will going to be a milestone in myproject but sir please guide me on how we send and receive mails if we have our own domain name like "" where rich mail is my domain name....Please....Please guide me on that as usual you are simply great and hats off to your dedication and curiosity to explain ASP.NET at the end I am eagerly waiting for your next post....thank you sir

Anonymous said...

@Abhinavsingh993, simply replace google domain name with yours and put your own smtp server (ask your admin if you don't know it) instead of googles.

Nothing else is google specific, it's standard mailing code in .NET

firoz said...

thanks bhijan i love u teacher

Prateek Diwakar said...

Dear Sir,

Please Give Some easy Examples For Learning JavaScripts..

Thank You

kamalkumar said...

while implementing this application i am getting error like you need 5.5.1 authentication required.
help me to avoid this error

satishintrug said...

i got an idea from this, thank you!

Akanksha Singh said...

Nice One..

yatin patel said...

thank you so much

Jhonattan Manrique said...

This code cannot be used in real life due to security (Sql Injection) and maintenance (Values that could be changed like connectionstring, smtp etc). For the people that could copy this code should bear this in mind.

Navjeet singh gaharwal said...

Thnx sir for the code..
This code help me to code in my project...

Tufan Nandi said...

please tech us MVC

Theresa Kang said...

using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))

can i replace with

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);

because I dont know how to declare the data source, integrated security and initial catalog.

Thank you

Zeeshan (zeex) said...

it seems that this article is written by a beginner, this should not be implement in real project. i just post some ideas.
1. store a unique key (salted or hash or encrypted) in database table while creating a user.
2. send an email link to the user login Email while submitting forgot password request. for example
3. confirm the link from user by clicking the link
4. match the link key with the stored key in database user table
5. show to reset password page.

This is the basic idea that should be implement in the real project.

Thank you.

sunita gupta said...

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

subhra said...

hello sir i am little bit confused about these 2 could be txtEmail.Text is same for both.please explain.thank you

Msg.From = New MailAddress(txtEmail.Text)


ITI NEGI said...

it was very helpful! thanks

naineshbca said...

sir , if Same email id associate with multiple email then what happen ???? As this code allow same email id to the multiple user ????

Anonymous said...

thanku so much it is very useful in my project

Anonymous said...

really helpful peace of code....
my professor give me 10 out of 10 for this code...
thank you sooooo much

Anonymous said...

100% working
can you please make some this kind of code that send someone FB password to our mail please

Semli Mustakin said...

Plz send some Ajax file m. .zip file to my email id ..sir..

Anonymous said...

I typed exactly the same ..but i get error that value of email should scalar..please help me

Anonymous said...

1) System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("", dr["email_id"].ToString(), "Reset Your Password", strBody.ToString());

2)System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("","cgp1234");
only this i chnaged in code but getting error that emailid must be scalar me

akash srivastava said...

sir i have a problum 5.5.1 authentication request how to solve this prob pls help me sir

akash srivastava said...

sir i have a problum 5.5.1 authentication request how to solve this prob pls help me sir

kishore said...

hi sir pls tell me i had same problem in 5.5.1 authentication request how to solve this prblm pls sir i need...


Give your Valuable Comments

Other Related Posts

© 2015 All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.