C# 2008R2服务器上的System.Net.Sockets.SocketException

C# 2008R2服务器上的System.Net.Sockets.SocketException,c#,smtp,gmail,C#,Smtp,Gmail,我有一个程序,我想在一个服务器上运行,它能够监视网络上的各种服务器,并在发生涉及这些服务器的特定情况时发送电子邮件通知 目前,我可以在本地机器上运行这个程序,并让它发送电子邮件(使用gmail SMTP)。但是,当我试图通过命令提示符在服务器上运行它时,它会引发以下异常: Unhandled Exception: System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable

我有一个程序,我想在一个服务器上运行,它能够监视网络上的各种服务器,并在发生涉及这些服务器的特定情况时发送电子邮件通知

目前,我可以在本地机器上运行这个程序,并让它发送电子邮件(使用gmail SMTP)。但是,当我试图通过命令提示符在服务器上运行它时,它会引发以下异常:

Unhandled Exception: 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
xxx.xxx.xxx.xxx:587
与发送电子邮件相关的代码相当简单:

static void sendEmail(MailAddressCollection mailCollection, string emailSender,
                      string emailDisplayName, string emailPassword,
                      string subject, string body) {

    MailAddress fromAddress = new MailAddress(emailSender, emailDisplayName);

    SmtpClient smtpClient = new SmtpClient {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, emailPassword)
    };

    MailMessage message = new MailMessage {
        From = fromAddress,
        Subject = subject,
        Body = body
    };

    foreach (MailAddress mailAddress in mailCollection) {
        message.To.Add(mailAddress);
    }

    smtpClient.Send(message);

}
所涉及的服务器是2008R2机箱,并且未启用Windows防火墙。此外,端口25肯定是开放的,因为此服务器可以发送其他类型的电子邮件(特别是由Dynamics CRM电子邮件路由器生成的电子邮件)


什么可能导致此错误?

此问题与Gmail阻止试图发送电子邮件的服务器的IP地址有关


当尝试使用Gmail帐户发送电子邮件时,首先尝试使用浏览器在特定IP地址的特定机器上手动登录Gmail。我最终不得不这样做,并通过验证来自我的服务器的电子邮件发送尝试(以编程方式生成)是否合法的过程。如果您没有像我一样经历这个过程,Gmail可以假定您的服务器不是合法的电子邮件发送者,并且可以继续假定来自您IP地址的所有通信都是无效的——直到您如上所述正式验证该IP地址。

“端口25肯定是打开的”,但脚本在端口587上使用smtp.Gmail.com。端口587打开了吗?我不知道如何检查,但我尝试了“netstat-a”,在列表中没有看到端口587。但我确实看到了端口25。在服务器上,尝试使用telnet。“telnet smtp.gmail.com 587”,看看你是否可以连接。我做了telnet测试,它也失败了:“连接到smtp.gmail.com…无法打开到主机的连接,在端口587上:连接失败”。然后我猜出站端口587在某个防火墙上被阻止。你在公司防火墙后面吗?您提到动态CRM可以发送电子邮件,为什么不使用与动态CRM相同的设置来发送电子邮件呢?