-2

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

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Ozeus
  • 59
  • 5
  • 1
    1. You should really be hashing users' passwords. 2. What error are you getting? – johnnyRose Sep 29 '17 at 19:12
  • How do you expect people to answer without the error? –  Sep 29 '17 at 19:12
  • Possible duplicate of [Sending email in .NET through Gmail](https://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail) – Cyber Progs Sep 29 '17 at 19:13
  • This doesn't answer your question, but what you are doing should be avoided: https://security.stackexchange.com/questions/17979/is-sending-password-to-user-email-secure very dangerous. – Michael Sep 29 '17 at 19:16
  • this is the error 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. – Ozeus Sep 29 '17 at 19:18
  • What is the exception it throws – user2526236 Sep 29 '17 at 19:21
  • @user2526236 An exception of type 'System.Net.Mail.SmtpException' occurred in System.dll but was not handled in user code Additional information: Failure sending mail. – Ozeus Sep 29 '17 at 19:23

1 Answers1

0

Try the below 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))
        {
            var fromAddress = new MailAddress("from@gmail.com", "From Name");
            var toAddress = new MailAddress("to@example.com", "To Name");
            const string fromPassword = "fromPassword";
            const string subject = "Subject";
            const string body = string.Format("Hi {0},<br /><br />Your password is {1}.< br />< br /> Thank You.", username, password);

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                IsBodyHtml = true,
                Body = body
            })
            {
  //i will not push to PROD
  System.Net.ServicePointManager.ServerCertificateValidationCallback = 
 delegate(object s,                        
 System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
                smtp.Send(message);
                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.";
        }
user2526236
  • 1,408
  • 2
  • 14
  • 28
  • Error 1 The expression being assigned to 'body' must be constant – Ozeus Sep 29 '17 at 19:38
  • @Mr.Me Then remove the `const` keyword. – mason Sep 29 '17 at 19:42
  • yes I did that and it worked now I am getting this exception Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required – Ozeus Sep 29 '17 at 19:44
  • @Mr.Me Go to this link and Allow less secure apps: ON https://myaccount.google.com/lesssecureapps?pli=1 – user2526236 Sep 29 '17 at 19:46
  • @user2526236 thank you I have already enabled that before the previous error occurred but yea it still gives the same error – Ozeus Sep 29 '17 at 19:53
  • @Mr.Me I have updated the code. To return true for certificate manager . Please make sure you are keying in the correct password. – user2526236 Sep 29 '17 at 19:53