I'm developing a simple login page in c#. I'm implementing forgot password link while clicking the link I need to send an email with random number to the corresponding user.I have the added the code which I mentioned below
C# Code:
protected void Button1_Click(object sender, EventArgs e)
{
string username = string.Empty;
string password = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, [Password] FROM tbl_Detailstbl WHERE Email_Id = @Email"))
{
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.Read())
{
username= sdr["Name"].ToString();
password = sdr["Password"].ToString();
}
}
con.Close();
}
}
if (!string.IsNullOrEmpty(password))
{
MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text.Trim());
mm.Subject = "Password Recovery";
mm.Body = string.Format("Hi {0},<br /><br />Your password is {1}.<br /><br />Thank You.", username, password);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("sender@gmail.com","asfsdfg");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage.ForeColor = Color.Green;
lblMessage.Text = "Password has been sent to your email address.";
}
else
{
lblMessage.ForeColor = Color.Red;
lblMessage.Text = "This email address does not match our records.";
}
}
HTML Code :
<form id="form2" runat="server">
<div>
<fieldset style="width:380px;">
<legend>Recover Password By Email Or User Name</legend>
<table>
<tr>
<td>UserName : </td><td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2"> OR</td>
</tr>
<tr>`enter code here`
<td>Email Id : </td><td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<asp:RegularExpressionValidator ID="revEmailId" runat="server"
ErrorMessage="Please enter valid email address"
ControlToValidate="txtEmail" Display="Dynamic"
ForeColor="Red" SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td> </td><td>
<asp:Button ID="Button1" runat="server" Text="Send" onclick="Button1_Click"/></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="" OnClick="Button1_Click"></asp:Label>
</td>
</tr>
</table>
</fieldset>
</div>
</form>
My problem is when I try to send an email I'm getting an error:
" An exception of type 'System.Net.Mail.SmtpException' occurred in System.dll but was not handled in user code
Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."