'MailMessage System.Net.Mail.SmtpException, Error when trying to send email via C# form
hi im stuck and keep getting errors when trying to setup a send email for.
here's my using.system:
using System.Net;
using System.Web;
using System.Net.Mail;
i then have this code in my send email button.
private void BtnEmail_Click(object sender, EventArgs e)
{
try
{
string to = "[email protected]";
string from = "[email protected]";
string subject = "Test email";
string body = @"This is a test email";
MailMessage mail = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Credentials = new NetworkCredential ("[email protected]", "myPassword");
client.Port = 587;
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show("Mail Sent", "Success", MessageBoxButtons.OK);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n\n" + ex.StackTrace, "Exception");
}
}
it looks like the exception is being through at the "client.send(mail);" line.
the catch exception message is: Failure sending mail.. System.Net.Mail.SmtpException.
any idea whats going wrong here?? Thanks.
Solution 1:[1]
First you need understand the reason of this problem, you can use SMTPDIAG tool for this.
Try port 465 or 25 with SSL, because port 587 should be used with TLS.
Check Google documentation: https://support.google.com/mail/answer/78775?hl=en.
Check your firewall and your ethernet firewall, ports may be closed.
Solution 2:[2]
I was facing the same issue because Google block these type of less secure mail. Check your mail that you have used in the code. If you have got one mail from google saying allow access to less secure app you can turn it on. now you will start receiving the mail.
Solution 3:[3]
Use port 465 for gmail. 587 will not work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nikolai.serdiuk |
Solution 2 | Rahul Singh |
Solution 3 | Haney |