SmtpClient 无法在 google 云服务器上工作

SmtpClient not working on google cloud server

我有一个 SmtpClient,当我 运行 它是本地主机时它工作正常。但是,在 google 云服务器上 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

我的代码:

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);

有谁知道为什么?对于 .net 应用程序,我应该使用 Azure 而不是 google 云吗?

谢谢

怀疑 问题是端口 587 上的流量在 Compute Engine 上默认被阻止,已知 IP 地址除外。

来自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.

此外,来自 "Sending Email from an Instance" 文档:

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.

后一个文档页面提供了许多替代方法。