Google
 

Friday, August 1, 2008

Validating SMTP host information

This is a simple class to check if a connection to SMTP host is possible. It can be useful in case of gathering user input and the user is required to enter a valid smtp host.

The idea is simple, open a TCP connection to the host, and read the initial welcome message sent by the smtp host, it should start with response code 220.
I everything is ok, we need to end the sesion by sending QUIT command and close the connection.
For more information check RFC 821 SIMPLE MAIL TRANSFER PROTOCOL

I used Visual C# 2008 Express edition to build this example. You can check the code below, or download the code with a test application from this link:




public static class SmtpChecker
{
public static bool Check(string host,int port,out string welcomeMessage)
{
try
{
using (TcpClient smtp = new TcpClient(host, port))
using (StreamReader reader = new StreamReader(smtp.GetStream()))
{
welcomeMessage = reader.ReadLine();

//validate the reasponse
if (welcomeMessage.StartsWith("220", StringComparison.InvariantCulture))
{
//Send QUIT as recommended by RFC 821
try
{
using (StreamWriter w = new StreamWriter(smtp.GetStream()))
{
w.WriteLine("QUIT");
w.Flush();
string result =reader.ReadLine();
}
}
catch
{}

return true;
}
else
{
welcomeMessage = "";
return false;
}
}
}
catch (Exception)
{
welcomeMessage = "";
return false;
}
}
}

No comments: