smtp4dev is a great little tool for testing E-mail sending functionality in your application. Instead of setting up your own SMTP server and fighting your ISPs restrictions, smtp4dev sits in your system tray and acts like a mock SMTP server, catching instead of relying them on to their destination. You can then view the messages in the E-mail client of your choice. Unfortunately, developers have to remember to run smtp4dev before they start testing the application. If you are building an ASP.NET application, here’s a little trick that you can use to start smtp4dev when your application starts up. NOTE: Big thanks to Rob for suggesting this.
RageFeed has the following folder structure:
Assets Databases Libraries Source ... Web (our MVC application) ... Utilities smtp4dev.exe
When a developer launches the ASP.NET MVC application, we’d like for smtp4dev to be launched automatically (if it isn’t already running). Initially I was trying to make this problem harder than it was, exploring ways to perhaps have Visual Studio launch the process, but Rob’s suggestion was to just throw it in in the Application_Start event:
protected void Application_Start() { ... if (ConfigurationManager.AppSettings["Environment"] == "Development") { try { Smtp4Dev.Start(); } catch (Exception ex) { throw new InvalidOperationException("Unable to start Smtp4Dev, check that AppSettings.Environment is set correctly.", ex); } } }
This works, but you have to ensure that smtp4dev will only be launched when developers are testing things locally. I added an AppSetting that contains the current deployment’s environment (ie: Development, Staging, Production, etc). The app only attempts to run smtp4dev if the current environment is “Development”.
The actual smpt4dev bootstrapper is quite simple:
public static class Smtp4Dev { public static void Start() { if (Smtp4DevIsRunning()) { return; } var path = HttpContext.Current.Server.MapPath("~/") + @"..\..\Utilities\smtp4dev.exe"; Process.Start(path, ""); } private static bool Smtp4DevIsRunning() { return Process.GetProcessesByName("smtp4dev.exe").Length > 0; } }
Presto, when the application starts, it will launch smpt4dev if it isn’t already running.