How to validate SMTP server

白昼怎懂夜的黑 提交于 2019-12-03 03:42:17

Attempt to connect to the SMTP port, and ensure you get a line back from it that starts with "220 " and contains the letters "SMTP". A typical example response would be:

220 prod.monadic.cynic.net ESMTP Postfix (2.5.5)

Then be polite and send "QUIT\r\n" to hang up.

You can do some further testing, if you like, such as testing that the user can likely deliver messages. For this, you'd send a HELO command with your hostname (or any string, really), a MAIL FROM command using the user's e-mail address, and a RCPT TO:<example@example.com>. Most servers at that point will tell you if relaying is not allowed. (I'm assuming you're doing this from the computer from which you will later be sending mail.) So long as you QUIT after that, rather than issuing a DATA command and the message data, nothing will be sent.

Here's an example session, done from the shell using the "netcat" command, showing that my server exists, but will not relay mail for people from random IP addresses.

    $ nc prod.monadic.cynic.net. 25
    220 prod.monadic.cynic.net ESMTP Postfix (2.5.5)
    HELO cynic.net
    250 prod.monadic.cynic.net
    MAIL FROM:<cjs@cynic.net>
    250 2.1.0 Ok
    RCPT TO:<example@example.com>
    554 5.7.1 <example@example.com>: Relay access denied
    QUIT
    221 2.0.0 Bye
    $

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!