Search code examples
c#emailsmtpgmail

Can't send mails in C# : Error in system.dll


I'm trying this code in order to send to somewho user his password using the mail he enters.

SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]", "********");
//de qui, a qui, objet, sujet
MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);

Here is the error :

Une exception non gérée du type 'System.Net.Mail.SmtpException' s'est produite dans System.dll

Informations supplémentaires : Le serveur SMTP requiert une connexion sécurisée ou le client n'était pas authentifié. La réponse du serveur était : 5.5.1 Authentication Required. Learn more at

I'll Translate here :

An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll

Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

While I tried with two different gmails accounts, same error, I am certain that password is correct. When I change the port to 465 I get this error :

An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll Additional Information: The operation timeout expired.

I got to setting Timeout to 10000, 20000, and even 100000 and still nothing !

Please help thanks !


Solution

  • Be aware that gmail "locks" the account if you have tried a couple of times with no success. I tried different code samples with my private gmail account and everything failed. When I had read about the requirements from GMail, I created a new gmail account and got the same code to work.

    The code is pretty similar to yours, with the exception of NetworkCredentials. This is code is from another StackOverflow question (tried it with my private account with no success, because of the multiple attempts): Send email using System.Net.Mail through gmail

      //Code
      MailMessage mail = new MailMessage();
      mail.From = new System.Net.Mail.MailAddress("***@gmail.com");
      SmtpClient smtp = new SmtpClient();
      smtp.Port = 587; 
      smtp.EnableSsl = true;
      smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
      smtp.UseDefaultCredentials = false; 
      smtp.Credentials = new NetworkCredential(mail.From.Address, "****");  
      smtp.Host = "smtp.gmail.com";
    
      //recipient
      mail.To.Add(new MailAddress("***@gmail.com"));
    
      mail.IsBodyHtml = true;
      string st = "Test";
    
      mail.Body = st;
      smtp.Send(mail);