«

»

Nov 30

how to generate a random password and send to mail in asp.net

Hi,In this article I will explain you how to generate auto generated password and also how to send to generated password mails IDS

–> In this application I used GMAIL Credentials to send mails ,use your own maild SMPTS to send mails

–> GMAIL  SMTP = smtp.gmail.com

–> GMAIL PORT =587

–> Add using System.Net.Mail;

–> I written a method ” getRandomPassword()”  to generate random password

Step1:

–> Add a new webform with name ” RandomPassword.aspx”

–> Copy and paste below code in RAndomPassword.aspx

Pic1

[code language=”html”]

 

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

<!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>

<fieldset>

<legend>Generate Random Password To Mail</legend>

<table>

<tr>

<td align="right">

Email ID :

</td>

<td align="left">

<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td align="right">

</td>

<td align="left">

<asp:Button ID="btnGenerate" runat="server" Text="Generate"

onclick="btnGenerate_Click" />

</td>

</tr>

</table>

</fieldset>

</div>

</form>

</body>

</html>

[/code]

Step 2:

–> Copy and paste the below code in RandomPassword.cs

[code language=”csharp”]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net.Mail;

public partial class RandomPassword : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

private string getRandomPassword()

{

string allowedChars = "";

allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";

allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";

allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";

char[] sep = { ‘,’ };

string[] arr = allowedChars.Split(sep);

string passwordString = "";

string temp = "";

Random rand = new Random();

for (int i = 0; i < 8; i++)

{

temp = arr[rand.Next(0, arr.Length)];

passwordString += temp;

}

return passwordString;

}

protected void btnGenerate_Click(object sender, EventArgs e)

{

SmtpClient client = new SmtpClient("smtp.gmail.com");

var message = new MailMessage();

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

client.Port = 587;

client.UseDefaultCredentials = false;

client.Credentials = new System.Net.NetworkCredential("naseer526@gmail.com", "*******");

client.EnableSsl = true;

MailAddress SendFrom = new MailAddress("naseer526@gmail.com", "Naseer");

try

{

String password = getRandomPassword();

MailAddress SendTo = new MailAddress(txtEmail.Text);

message = new MailMessage(SendFrom, SendTo);

message.Subject = "Auto Generated Password";

message.Body = "Auto Generated Password has been generated, login using below creditiantials:<br/>" + "<br/>UserName :" + txtEmail.Text + "<br/>Password :" + password;

message.IsBodyHtml = true;

message.Priority = MailPriority.High;

client.ServicePoint.MaxIdleTime = 0;

client.ServicePoint.ConnectionLimit = 1;

client.Send(message);

ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE=’javascript’>alert(‘Mail Sent successfully’);</script>");

}

catch

{

ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE=’javascript’>alert(‘Unexpected Error Occur TryAgain ‘);</script>");

}

}

}

[/code]

O/P Screen:

pic2

Happy Coding!!!

Admin.

6 comments

Skip to comment form

  1. sanjeev

    After using your above Code i got the this type of error please help me & give the best solution:
    Thanks Advance..

    System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at Resume_Maker_Project.WebForm6.Button2_Click(Object sender, EventArgs e) in E:Resume_Maker_ProjectResume_Maker_ProjectResume_Maker_ProjectWebForm6.aspx.cs:line 66

    1. Punit

      using System.Net.Mail;

      SmtpClient smtp = new SmtpClient();
      smtp.Host = “smtp.gmail.com”;
      smtp.Port = 587;
      smtp.Credentials = new System.Net.NetworkCredential(“yourmailid@gmail.com”, “password”);
      smtp.EnableSsl = true;
      smtp.Send(MailMsg);

  2. Punit

    using System.Net.Mail;

    —-
    SmtpClient smtp = new SmtpClient();
    smtp.Host = “smtp.gmail.com”;
    smtp.Port = 587;
    smtp.Credentials = new System.Net.NetworkCredential(“yourmailid@gmail.com”, “password”);
    smtp.EnableSsl = true;
    smtp.Send(MailMsg);

  3. Naseer

    Thanks Punit.

  4. EDWINA

    i have tried everything but its giving (The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. )error
    string password = CreateRandomPassword(8);
    MailMessage msg = new MailMessage();
    msg.From = new MailAddress(“edwina.rosie@gmail.com”);
    msg.To.Add(TextBoxemail.Text);
    msg.Subject = “wlecome our website”;
    msg.Body = “Thank u for registering our website your password is”+password;
    msg.IsBodyHtml = true;

    SmtpClient smtp = new SmtpClient();
    smtp.Host = “smtp.gmail.com”;
    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
    NetworkCred.UserName = “edwina.rosie@gmail.com”;
    NetworkCred.Password = “TZTW6BKE “;
    smtp.UseDefaultCredentials = true;
    smtp.Credentials = NetworkCred;
    smtp.Port = 587;
    smtp.EnableSsl = true;
    smtp.Send(msg);
    smtp.Timeout = 20000;

    SqlCommand cmd3 = new SqlCommand(“insert into Login values(‘” + TextBoxemail.Text + “‘,'”+password+”‘)”, con);
    cmd3.ExecuteNonQuery();

  5. Hosting

    I was doing something like this recently to generate an 8 byte random string from 62 characters. The characters were 0-9,a-z,A-Z. I had an array of them as was looping 8 times and picking a random value out of the array. This was inside a rails app.

Leave a Reply to EDWINA Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>