Search code examples
c#emailsmtpgmail

C# - Sending an email, via Gmail or Other?


Server: VDS

OS: Windows Server 2008 R2

Application: None

Library (DLL used by an application): Yes, C#

I am trying to send mail via C# using from what I read, gmail service. Basically just a test email to myself would be a start to know it works. If you have to ask, the information is stored in config.json file rather than directly in the code, hence the "AccountRecovery.AccountRecoveryConfig".

I cannot seem to get it to work! When using certain ports I get different errors!

PORT 465 - With Credentials ERROR:

2016-02-05 02:52:33 - Command: ERROR: System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.

PORT 587 - With Credentials ERROR:

2016-02-05 02:55:50 - Command: ERROR: System.Net.Mail.SmtpException: 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

I have no idea what to do. Am I doing something wrong?

    public static void SendEmail(string email)
    {
        MailMessage mail = new MailMessage(AccountRecovery.AccountRecoveryConfig.ServerEmailAddress, email);
        SmtpClient client = new SmtpClient();
        client.Timeout = 30000;
        client.Host = AccountRecovery.AccountRecoveryConfig.HostSMTPServer;
        client.Port = AccountRecovery.AccountRecoveryConfig.HostPort;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential(AccountRecovery.AccountRecoveryConfig.ServerEmailAddress, AccountRecovery.AccountRecoveryConfig.ServerEmailPassword);
        client.EnableSsl = true;
        //client.ServicePoint.MaxIdleTime = 1;
        mail.Subject = AccountRecovery.AccountRecoveryConfig.EmailSubjectLine;
        mail.Body = AccountRecovery.AccountRecoveryConfig.EmailBodyLine;
        mail.IsBodyHtml = false;
        client.Send(mail);
    }

Solution

  • The correct port is 587 for google, this error:

    2016-02-05 02:55:50 - Command: ERROR: System.Net.Mail.SmtpException: 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

    You should give access to less secure applications. Here is the LINK where you can do it for your current logged google account.