Many of the systems I have been working on required sending email messages as part of certain use cases: email address confirmation, notifications, system monitoring reports, etc. When working for a company, I usually use their SMTP server to send testing emails when running in the development environment. But for my own projects, that’s not a solution, since I do not run an SMTP server at home. Connecting my personal email account and storing credentials in source control does not seem like a viable solution either, since I’m sometimes working with other developers too. Luckily, there is a simple solution for use in development environments.
Sending emails using SmtpClient can be pretty straightforward:
SmtpClient smtp = new SmtpClient(); smtp.Send("firstname.lastname@example.org", "email@example.com", "Test email", "This is a test email message.");
The parameterless constructor of SmtpClient uses configuration values from element in app.config or web.config. The attribute deliveryMethod of this element can be set to an option specifiedPickupDirectory – with this option set, SmtpClient does not send email message through network (like the network option does), but instead saves the message into a file in specified directory. The configuration can look something like this to save messages to “C:\Temp\” directory:
<system.net> <mailSettings> <smtp deliveryMethod="SpecifiedPickupDirectory" from="firstname.lastname@example.org"> <specifiedPickupDirectory pickupDirectoryLocation="C:\Temp\" /> </smtp> </mailSettings> </system.net>
Now every time that SmtpClient.Send is called, a file will be created at the specified directory containing the message. These files can even be opened just like any other email messages in Outlook.
This is the configuration that I’m now using for running in my development environment. For the production/release configuration, I’m using Web.config transformations to change the settings automatically to use a real SMTP server. The best thing? There are no changes in the source code required to switch between environments.