Search code examples
c#windows-server-2012-r2

c# gmail connection failed because connected host has failed to respond


I'm trying to send a mail with my gmailaccount from a server with the following code.

            var fromAddress = new MailAddress("[email protected]", "xxxxxx");
        var toAddress = new MailAddress(toMailAddress);
        const string fromPassword = "xxxxx";

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            IsBodyHtml = true,
            Subject = mailSubject,
            Body = htmlBody
        })
        {
            smtp.Send(message);
        }

This gives the next result when I deploy it on my windows server although I have an Inobound Rule for port 587 on the firewall. It works perfect when I test it local

connectionFailed


Solution

  • I too have faced this problem. Actually Gmail does not allow to access gmail for sending mails for less secure apps. Perform the following steps: if you are getting exception like

    "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"
    
    1. Go to your google account "My Account".
    2. under "Sign-in & security" go to the bottom, you will find "Allow less secure apps: OFF", you need to turn it on by clicking the button next to it.
    3. Now your gmail account will be accessible from your code.