Resources » .NET programming » ASP.NET/Web Applications

Generating Random Password and mail it to the user emailid.

Updated: Category: ASP.NET/Web Applications
Author: Member Level: GoldPoints: 80

In this article i am explaning the logic for creating random password and mail it to the user. If the user forgets his/her password then we can use this logic of generating random password for sending him the new password by emailid.

You all must have observed this many times in your day to day activities that when we forget our passwords and want to generate a new one the website automatically sends a randomly generated password on our email id. I would here be providing you with a code snippet for randomly generating passwords and emailing it to user's email id automatically.

The steps of execution would be as follows:
1. First we will check whether the User with the supplied username exist or not.
2. If user exist we will read its detail like name,username and emailid from the table.
3. Then we will generate the random password.
4. At last we will send the password to the emailid of the user.

Below is the codes for all the steps:

protected void btnforget_Click(object sender, EventArgs e)
string username = txtUser.Text.Trim();
string connection = ConfigurationManager.ConnectionStrings["HospitalConnectionString"].ToString();
int newid;
SqlConnection con = new SqlConnection(connection);

// IsValidUser is the stored procedure which will check whether user with the specific username exist or not.

SqlCommand command = new SqlCommand("IsValidUser", con);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@UserName", System.Data.SqlDbType.VarChar, 100)).Value = username;
command.Parameters.Add(new SqlParameter("@UserID", System.Data.SqlDbType.Int, 4)).Direction = System.Data.ParameterDirection.Output;
newid = (int)command.Parameters["@UserID"].Value;
if (newid == 1)
command = new SqlCommand("SELECT * FROM User_Info WHERE UserName='" + username + "'", con);
SqlDataReader reader;
reader = command.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
int UserId = Convert.ToInt32(reader["Id"]);
string FirstName = reader["FirstName"].ToString();
string LastName = reader["LastName"].ToString();
string EmailId = reader["EmailId"].ToString();
string UserName = reader["UserName"].ToString();
/*CreateRandomPassword() method will genearte the randow password.*/

string password = CreateRandomPassword(8);

//UPdatePassword() method will update the password in the database.

UPdatePassword(UserId, FirstName, LastName, EmailId, username, password);
else if (newid == -1)
ScriptManager.RegisterStartupScript(this, this.GetType(), "Invalid User : ", "<SCRIPT LANGUAGE='javascript'>alert('User De-activated');</script>", false);
btnLogin.Enabled = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Invalid User : ", "<SCRIPT LANGUAGE='javascript'>alert('Invalid User');</script>", false);
catch (Exception ex)
//trace error
string log = ex.Message;

private void UPdatePassword(int UserId, string FirstName, string LastName, string EmailId, string username, string password)
string connection = ConfigurationManager.ConnectionStrings["HospitalConnectionString"].ToString();

string sql = "UPDATE User_Info SET Password = @password WHERE id=" + UserId + "";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(sql, con);
SqlParameter[] pram = new SqlParameter[1];
pram[0] = new SqlParameter("@password", SqlDbType.VarChar, 50);
pram[0].Value = password;
for (int i = 0; i < pram.Length; i++)

//////////////////////////////////////email code/////////////////////////////////////////
MailMessage MyMailMessage = new MailMessage();
MyMailMessage.From = new MailAddress("", "donotreply");//mail id and display name

MyMailMessage.Subject = "Login Credentials";
MyMailMessage.IsBodyHtml = true;

string body = "Hi " + Fname + "," + Lname + "
Your Credentials are as follows:
Username: " + UserName + "
Password: " + password + "";
MyMailMessage.Body = body;

System.Net.Mail.SmtpClient SMTPServer = new SmtpClient("");
SMTPServer.Port = 587;
SMTPServer.Credentials = new System.Net.NetworkCredential("", "care@12");//mail id and password
SMTPServer.EnableSsl = true;
lblstatus.Visible = true;
lblstatus.Text = " Credentials has been sent to your account. please check.";
catch (Exception ex)
lblstatus.Text = "Unable to send mail.";

private string CreateRandomPassword(int PasswordLength)
string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
return new string(chars);

Below is the table structure:

CREATE TABLE [dbo].[User_Info](
[id] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NULL,
[UserName] [varchar](100) NOT NULL,
[Phone] [varchar](50) NOT NULL,
[Password] [varchar](100) NULL,
[EmailId] [varchar](50) NOT NULL,
[RoleId] [varchar](50) NULL,
[UserTheme] [varchar](50) NULL,
[LastLoginDate] [varchar](50) NULL,
[IsLoggedIn] [bit] NULL,
[IsActive] [bit] NULL

Following the Code of "IsValidUser" Stored procedure.

CREATE PROCEDURE [dbo].[IsValidUser]
@UserName [varchar](100),
@UserID [int] OUTPUT

IF EXISTS (SELECT * FROM User_Info WHERE Username = @UserName AND IsActive = 1)
SET @UserID = 1
IF EXISTS (SELECT * FROM User_Info WHERE Username = @UserName AND IsActive = 0)
SET @UserID = -1
SET @UserID = 0

Did you like this resource? Share it with your friends and show your love!

Responses to "Generating Random Password and mail it to the user emailid."

No responses found. Be the first to respond...


Post Comment:

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)

    Type the numbers and letters shown on the left.

    Submit Article     Return to Article Index
    Subscribe to Subscribers
    Awards & Gifts
    Talk to Webmaster Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India