Friday, July 30, 2010

SMTP Connection Test Script with ASP.NET


Slightly off topic today, one of the few posts not about Sitecore CMS.
A small challenge I had to deal with – troubleshoot a number of SMTP servers, trying to figure out which one can actually relay.
As basic as this sounds, I have not found a ready to go ASP.NET script on the web that can help me. So I decided to build my own.

The idea is simple – use standard SmtpClient class, wrap the Send() method in try/catch and output the exception.

SmtpClient client = new SmtpClient(server, int.Parse(port));
client.Credentials = new System.Net.NetworkCredential(username, password);
MailMessage mailMessage = new MailMessage(from, to);
mailMessage.Subject = "Test Email";
mailMessage.Body = "Hello, this is a test email from BayNET. Please ignore.";
try
{
   // trying to send...
   client.Send(mailMessage);
   Response.Write("Success!!!");
}
// catching SmtpException 
catch (SmtpException exception)
{
   Response.Write(String.Format("Cannot send mail. Status Code {0}. Details:{1}", exception.StatusCode, exception.Message));
}

The files can be downloaded from here.

Ideas were taken pretty much from the folks at stackoverflow.com.

Happy SMTP relaying!

0 comments: