SmtpClient not working on google cloud server

I have an SmtpClient that works fine when I run it localhost. However, on google cloud server it returns:

System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xx.xx.xx:587

My code:

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("User email");
mailMessage.From = new MailAddress("My Company Email");
mailMessage.Subject = "Test";
mailMessage.Body = "MSG Test";

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.mycompany.com"; //Or Your SMTP Server Address
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("email@mycompany.com", "password");
smtp.Send(mailMessage);

Does anyone know why? Should I use Azure instead of google cloud for .net applications?

Thanks

Jon Skeet
people
quotationmark

I suspect the problem is that traffic on port 587 is blocked by default on Compute Engine, except for known IP addresses.

From the firewall documentation:

Compute Engine blocks or restricts traffic through all of the following ports/protocols between the Internet and virtual machines, and between two virtual machines when traffic is addressed to their external IP addresses through these ports (this also includes load-balanced addresses). These ports are permanently blocked; they cannot be opened using firewall rules.

  • ...
  • Most outgoing traffic to port 465 or 587 (SMTP over SSL) is blocked, except for known Google IP addresses.

Also, from the "Sending Email from an Instance" documentation:

Google Compute Engine does not allow outbound connections on ports 25, 465, and 587. By default, these outbound SMTP ports are blocked because of the large amount of abuse these ports are susceptible to. In addition, having a trusted third-party provider such as SendGrid, Mailgun, or Mailjet relieves Compute Engine and you from maintaining IP reputation with your receivers.

This latter documentation page provides a number of alternative approaches.

people

See more on this question at Stackoverflow