Thursday, August 18, 2011

Sending Confirmation Password to the mailing address in .NET

Add a button and text box in aspx page and write the code in the button_Click for sending a password to customer's mail address
The IIS server should be configured to SMTP server.Keep in mind before start writing the code in the code behind file.

using System.Net.Mail;

private void button_Click()
{

bool password=ConfirmSendNewPwd(TextBoxName.Text);
if(password == true)
{
Response.Write("Mail Sent Successfully");
}

}

bool ConfirmSendNewPwd(string strEmail)
{
bool bSuccess = false;
strnewpwd = RandomPWD();//This Random Password Generation Code is there in my past published posts....
string strnewpwd = string.Empty;
try
{
if (//Database updated successfully)
{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("your.own@mail-address.com");
mailMessage.From = new MailAddress("another@mail-address.com");
mailMessage.Subject = "ASP.NET e-mail test";
mailMessage.Body = GetForgetPWDEmailMessage(strnewpwd);
SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
smtpClient.Send(mailMessage);
bSuccess = true;
return bSuccess;
}
return bSuccess;
}
catch (Exception ex)
{
string errMsg = ex.Message;
return bSuccess;
}
}

string GetForgetPWDEmailMessage(string strnewpwd)
{
StringBuilder sbBody = new StringBuilder();
sbBody.Append("Dear User")
.Append("," + Environment.NewLine)
.Append(Environment.NewLine)
.Append("Your new password to website is: " + strnewpwd)
.Append(Environment.NewLine)
.Append(Environment.NewLine)
.Append("Regards," + Environment.NewLine)
.Append("WebSite.")
.Append(Environment.NewLine)
.Append(Environment.NewLine)
.Append("Note : This email is automatically generated from Website registration process. Please do not reply to this email. This mailbox is not monitored and you may not receive any response. For any kind of assistance, please mail to ")
.Append(Environment.NewLine)

return sbBody.ToString();
}