.Net TcpClient 和 SmtpClient 不会连接到我的 Smtp 服务器 [英] .Net TcpClient and SmtpClient won't connect to my Smtp server

查看:52
本文介绍了.Net TcpClient 和 SmtpClient 不会连接到我的 Smtp 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以连接到 Smtp 服务器以查看它是否在线.此方法适用于测试许多邮件服务器,但不是所有邮件服务器.代码如下,但是失败发生在...

I have a method that is supposed to connect to an Smtp Server to see if it is online. This method works when testing many mail servers, but not all of them. The code is below, however the failure happens on...

client.Connect(strMailServer, intPort);

client.Connect(strMailServer, intPort);

... 在与服务器对话的逻辑甚至开始之前.它根本不会连接.我已经确定我连接的是正确的 IP 和端口 (25),并且我已经使用第三方网站(如 mxtoolbox)成功测试了相同的服务器 IP.此服务器正在接收来自万维网的常规流量...只有 .Net 似乎无法连接.我已经查看了防火墙规则,并使用 WireShark 进行了观察以查看服务器上发生的情况,但是我从未看到任何来自测试运行的传入数据包.防火墙设置为允许任何人在所有接口上连接到端口 25.

... before the logic of talking to the server even begins. It simply won't connect. I've made absolutely sure I'm connecting the the right IP and port (25), and I've used third party web sites like mxtoolbox to test the same server IP with success. This server is receiving regular traffic from the world wide web... only .Net seems unable to connect. I've reviewed firewall rules, and watched with WireShark to see what is happening on the server, but I never see any incoming packets from my test runs. The Firewall is set to allow all connections to port 25 on all interfaces, from anybody.

我还使用 SmtpClient 运行了如下所示的类似测试,它也失败了.

I've also used SmtpClient to run a similar test shown below, it fails as well.

                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: {"无法建立连接,因为目标机器主动拒绝它xxx.xxx.xxx.xxx:25"}

The error stack here leads to the same underying error as my TcpClient attempt. SocketException: {"No connection could be made because the target machine actively refused it xxx.xxx.xxx.xxx:25"}

世界上的每个人怎么能连接到这个服务器...除了我的笔记本电脑...我不认为这是防火墙问题.

How could everybody in the world be able to connect to this server... except for my laptop computer... I don't think this is a firewall issue.

帮助!

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 上的所有连接,包括入站和出站.一旦我搬到不同的地方,一切都奏效了.呸!!

The answer was so simple I slapped myself with I realized... My ISP is blocking all connections on port 25, inbound and outbound. As soon as I moved to a different location everything worked. Duh!!

http://www.cox.com/residential/support/internet/article.cox?articleId=cacf82f0-6407-11df-ccef-000000000000

对于可能需要它的人,这里是我的 SMTPTest 类,它将探测服务器的 SMTP 功能.我用它来监控我的服务器、报告中断并验证用户输入的服务器信息.

For whoever might want it, here is my SMTPTest class that will probe a server for SMTP capability. I use it to monitor my servers, report outages, and validate user input of server info.

public struct SMTPTestResult
{
    public string Server;
    public bool Found;
    public bool OriginalPortSuccess;
    public int FinalPort;
    public bool UsedSSL;
    public string Response;
}

public class SMTPTest
{
    public static SMTPTestResult TestMailServer(string MailServer)
    {
        return TestMailServer(MailServer, 25, true);
    }

    public static SMTPTestResult TestMailServer(string MailServer, int Port, bool TryOtherPorts)
    {
        SMTPTestResult result = new SMTPTestResult();
        result.Server = MailServer;

        if (AttemptMailServer(MailServer, Port, false, out result.Response))
        {
            //First try the requested port, without SSL.
            result.Found = true;
            result.UsedSSL = false;
            result.OriginalPortSuccess = true;
            result.FinalPort = Port;
            return result;
        }
        else if (AttemptMailServer(MailServer, Port, true, out result.Response))
        {
            //Try the requested port, with SSL.
            result.Found = true;
            result.UsedSSL = true;
            result.OriginalPortSuccess = true;
            result.FinalPort = Port;
            return result;
        }
        else if (TryOtherPorts && Port != 465 && AttemptMailServer(MailServer, 465, true, out result.Response))
        {
            //Try port 465 with SSL
            result.Found = true;
            result.UsedSSL = true;
            result.OriginalPortSuccess = false;
            result.FinalPort = 465;
            return result;
        }
        else if (TryOtherPorts && Port != 25 && AttemptMailServer(MailServer, 25, false, out result.Response))
        {
            //Try port 25, without SSL.
            result.Found = true;
            result.UsedSSL = false;
            result.OriginalPortSuccess = false;
            result.FinalPort = 25;
            return result;
        }
        else if (TryOtherPorts && Port != 25 && AttemptMailServer(MailServer, 25, true, out result.Response))
        {
            //Try port 25, with SSL.
            result.Found = true;
            result.UsedSSL = true;
            result.OriginalPortSuccess = false;
            result.FinalPort = 25;
            return result;
        }
        else if (TryOtherPorts && Port != 587 && AttemptMailServer(MailServer, 587, false, out result.Response))
        {
            //Try port 587, without SSL.
            result.Found = true;
            result.UsedSSL = false;
            result.OriginalPortSuccess = false;
            result.FinalPort = 587;
            return result;
        }
        else if (TryOtherPorts && Port != 587 && AttemptMailServer(MailServer, 587, true, out result.Response))
        {
            //Try port 587, with SSL.
            result.Found = true;
            result.UsedSSL = true;
            result.OriginalPortSuccess = false;
            result.FinalPort = 587;
            return result;
        }
        else
        {
            result.Found = false;
            result.OriginalPortSuccess = false;
            result.FinalPort = Port;
            return result;
        }
    }

    private static bool AttemptMailServer(string strMailServer, int intPort, bool blnSSL, out string strResponse)
    {
        try
        {
            if(!blnSSL)
            {
                //I'll try a basic SMTP HELO
                using (var client = new TcpClient())
                {
                    client.Connect(strMailServer, intPort);
                    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 (strResponse.StartsWith("220"))
                                return true;
                            else
                                return false;
                        }

                    }
                }
            }
            else
            {
                //I'll try with SSL
                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 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 (strResponse.StartsWith("220"))
                                return true;
                            else
                                return false;
                            // GMail responds with: 220 mx.google.com ESMTP
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            strResponse = ex.Message;
            return false;
        }
    }

}

这篇关于.Net TcpClient 和 SmtpClient 不会连接到我的 Smtp 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆