I am trying to implement this in my e commerce website whereby users can get their passwords if they forget it. I have looked at some codes in the Internet and tried to implement it but it shows me failure in sending email. I blocked my firewall tried different ports but nothing worked. I also looked at some question previously asked here but nothing worked.
Here is the code:
string username = string.Empty;
string password = string.Empty;
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\SHEHAB\Documents\Visual Studio 2013\WebSites\password\App_Data\LoginDB.mdf;Integrated Security=True");
using (SqlCommand cmd = new SqlCommand("SELECT Username, [Password] FROM Users WHERE Email = @Email"))
{
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.Read())
{
username = sdr["Username"].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;
NetworkCredential NetworkCred = new NetworkCredential();
NetworkCred.UserName = "sender@gmail.com";
NetworkCred.Password = "Password";
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.";
}
The error happens on this line of code:
smtp.Send(mm);
and this is the exception I get:
An exception of type 'System.Net.Mail.SmtpException' occurred in System.dll but was not handled in user code
Additional information: Failure sending mail.
Any thoughts? Thanks