How to validate SMTP server

后端 未结 2 1326
臣服心动
臣服心动 2021-02-06 12:59

I am working on a project where I have to validate the given SMTP server i.e in a textbox user will provide the detail and then he will click on a test button. I want to check w

2条回答
  •  猫巷女王i
    2021-02-06 13:26

    You might want to improve on this quick code with proper exception handling and maybe also setting the timeouts - it takes about 15 seconds to fail if it can't connect but that might be a limitation of the TCP/IP handshaking.

    And sending a QUIT command as Curt suggested would be nice.

    private bool ValidSMTP(string hostName)
    {
        bool valid = false;
        try
        {
            TcpClient smtpTest = new TcpClient();
            smtpTest.Connect(hostName, 25);
            if (smtpTest.Connected)
            {
                NetworkStream ns = smtpTest.GetStream();
                StreamReader sr = new StreamReader(ns);
                if (sr.ReadLine().Contains("220"))
                {
                    valid = true;
                }
                smtpTest.Close();
            }
        }
        catch
        {
    
        }
        return valid;
    }
    

提交回复
热议问题