0
votes

So, I am working on windows Forms and trying so send email with smtp. Here is a Code:

MailMessage mail = new MailMessage(from, to, subject, text);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 465;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(from, password);

try
{
    client.Send(mail);
    MessageBox.Show("Mesage has benn sant");
}
catch (Exception ex)
{
    MessageBox.Show("Failure while sending message");
    MessageBox.Show(ex.Message);
}

When I run this Code I am getting Following Error:

"Failure sending email".

When I changed port to 587 I have got following:

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication REquired".

So why I cannot send email ? Can someone explain me that ?

I have changed port to 25 and have sent mail from hotmail( I have replaced "smtp.gmail.com" with "smtp.live.com"), not from gmail. And it works. Seems it's something wrong with gmail.

3

3 Answers

0
votes

I was able to make your code work by adding the following three lines and making change in the gmail account setting:

        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential (from, password);

In addition to the above changes, it turns out, you also need to update your google account settings and allow less secure apps.

I learned about this on this thread: Sending email in .NET through Gmail

Hope this helps.

0
votes

Firstly change the port to 25.

Also, the arguments for client.Credentials are supposed to be your username and password to login with. For example...

client.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");
-1
votes

I had the same problem. Was able to fix it by disabling this security setting:

going to this link and turning on "access for less secure apps"

https://www.google.com/settings/security/lesssecureapps

enter image description here