tags:

views:

384

answers:

4

How can I test SMTP is up and running via C# without sending a message.

I could of course try:

try{
// send email to "[email protected]"
}
catch
{
// log "smtp is down"
}

There must be a more tidy way to do this.

+2  A: 

You could open up the port (25) with a socket or TcpClient and see if it responds.

Daniel A. White
+2  A: 

Open a socket connection to the smtp server on port 25 and see if you get anything. If not, no smtp server.

Justin Niessner
+10  A: 

You can try saying EHLO to your server and see if it responds with 250 OK. Of course this test doesn't guarantee you that you will succeed sending the mail later, but it is a good indication.

And here's a sample:

class Program
{
    static void Main(string[] args)
    {
        using (var client = new TcpClient())
        {
            var server = "smtp.gmail.com";
            var port = 465;
            client.Connect(server, port);
            // 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(server);
                using (var writer = new StreamWriter(sslStream))
                using (var reader = new StreamReader(sslStream))
                {
                    writer.WriteLine("EHLO " + server);
                    writer.Flush();
                    Console.WriteLine(reader.ReadLine());
                    // GMail responds with: 220 mx.google.com ESMTP
                }
            }
        }
    }
}

And here's the list of codes to expect.

Darin Dimitrov
+1: Very elegant, using the protocol correctly.
Reed Copsey
Liking it - liking it a lot! Good one Darin!
Vidar
A: 

Here is a nice open source tool (does more than MX): http://www.codeproject.com/KB/IP/DNS_NET_Resolver.aspx

John