I am developing a small application in asp.net using C#, where if user forgets password, I want to send the password from database to user's mail when clicked on forget password button. I was successful in sending the password in an email but in local machine. The settings which I am using, on the local machine, I used on the server too. But if I try on the server, I was thrown with an error saying "Failure sending email". Can anybody please tell me where I am making a mistake and what to do further if it has to work in server.
Below is my code :
try
{
if (ds.Tables[0].Rows.Count > 0)
{
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("mymail@gmail.com");
Msg.To.Add(new MailAddress(txtboxforgotemail.Text));
Msg.Subject = "Forgot Password :";
Msg.Body = "Hi, Dear '" + ds.Tables[0].Rows[0]["username"] + "' , your password is:" + ds.Tables[0].Rows[0]["password"] + "";
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential ("mymail@gmail.com","mypassword");
smtp.Send(Msg);
lblforgotemail.Text = "Your Password Details Sent to your mail";
txtboxforgotemail.Text = "";
}
else
{
lblforgotemail.Text = "The email you entered does not exist.";
}
}
catch (Exception ex)
{
txtboxforgotemail.Text = "";
lblforgotemail.Text = ex.Message;
}
I've got the exact same thing working in a live environment, the only difference is I have the following properties set on my smtp class as well:
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
I got the same issue few days back. Remove smtp.Port = 587 from your code and it will work
try
{
string admin_email = "youremail"
string admin_emailpwd = "your pwd"
MailMessage mail = new MailMessage();
mail.To.Add(SendTo);
mail.From = new MailAddress(admin_email);
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "SMTP.gmail.com";
// smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential(admin_email, admin_emailpwd);
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch
{
return false;
}
return true;
}
This is my code and it works too. (NOTE: I've commented smtp.port)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.