【发布时间】:2014-08-19 18:02:43
【问题描述】:
我有一个方法应该连接到 Smtp 服务器以查看它是否在线。此方法适用于测试许多邮件服务器,但不是全部。代码如下,但是失败发生在...
client.Connect(strMailServer, intPort);
... 在与服务器对话的逻辑开始之前。它根本不会连接。我已经确定我连接了正确的 IP 和端口 (25),并且我已经使用第三方网站(如 mxtoolbox)成功地测试了相同的服务器 IP。此服务器正在接收来自万维网的常规流量……只有 .Net 似乎无法连接。我已经查看了防火墙规则,并使用 WireShark 查看了服务器上发生的情况,但我从未看到任何来自我的测试运行的传入数据包。防火墙设置为允许从任何人到所有接口上的端口 25 的所有连接。
我还使用 SmtpClient 运行了类似的测试,如下所示,它也失败了。
var client = new System.Net.Mail.SmtpClient(strMailServer, intPort);
client.Send("test@mydomain.com", "test@mydomain.com", "test message", "This is meant to test an SMTP server to see if it is online, it expects the message to be rejected.");
这里的错误堆栈导致与我的 TcpClient 尝试相同的潜在错误。 SocketException: {"No connection could be made because the target machine主动拒绝xxx.xxx.xxx.xxx:25"}
世界上的每个人都怎么能连接到这个服务器...除了我的笔记本电脑...我不认为这是防火墙问题。
救命!
public static bool TestMailServer(string strMailServer, int intPort, out string strResponse)
{
try
{
try
{
//First I'll try a basic SMTP HELO
using (var client = new TcpClient())
{
client.Connect(strMailServer, intPort);
// As GMail requires SSL we should use SslStream
// If your SMTP server doesn't support SSL you can
// work directly with the underlying stream
using (var stream = client.GetStream())
{
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.WriteLine("EHLO " + strMailServer);
writer.Flush();
strResponse = reader.ReadLine();
if (strResponse == null)
throw new Exception("No Valid Connection");
stream.Close();
client.Close();
if (F.StartsWith(strResponse, "220"))
return true;
else
return false;
}
}
}
}
catch (Exception ex)
{
//If the above failed, I'll try with SSL
using (var client = new TcpClient())
{
//var server = "smtp.gmail.com";
//var port = 465;
//client.SendTimeout = 10000;
//client.ReceiveTimeout = 10000;
client.Connect(strMailServer, intPort);
// As GMail requires SSL we should use SslStream
// If your SMTP server doesn't support SSL you can
// work directly with the underlying stream
using (var stream = client.GetStream())
using (var sslStream = new SslStream(stream))
{
sslStream.AuthenticateAsClient(strMailServer);
using (var writer = new StreamWriter(sslStream))
using (var reader = new StreamReader(sslStream))
{
writer.WriteLine("EHLO " + strMailServer);
writer.Flush();
strResponse = reader.ReadLine();
if (strResponse == null)
throw new Exception("No Valid Connection");
stream.Close();
client.Close();
if (F.StartsWith(strResponse, "220"))
return true;
else
return false;
// GMail responds with: 220 mx.google.com ESMTP
}
}
}
}
}
catch (Exception ex)
{
strResponse = ex.Message;
return false;
}
}
【问题讨论】:
-
我的 ISP 阻止了端口 25 上的所有连接,包括入站和出站。当我搬到另一个地方时,一切都正常了。呸!! cox.com/residential/support/internet/…
-
在端口 25 上阻止出站流量是很常见的。许多 SMTP 服务器还侦听端口 587,该端口不太常见。
标签: c# .net smtp tcpclient smtpclient