How to demo and test sending email

Making your application send email is a pretty common requirement. But without setting up your very own development SMTP server to actually send that email, how can you demonstrate that capability to the stakeholder or test that it works?

The sample below shows how to send email locally on your workstation. The email will appear as a .eml file in a specified folder. Double-click on the .eml file and it will open in Outlook.

using System.Net.Mail;

namespace SmtpDemo
  class Program
    static void Main( string[] args )
      // Note: In .NET 4.0, System.Net.Mail.SmtpClient implements IDisposable;
      // .NET 3.5 and earlier it does not.
      using ( var smtpClient =
                  new SmtpClient( "localhost" )
                    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                    PickupDirectoryLocation = @"C:\Users\visualstuart\Desktop"
                  } )
        string from = "<a href=""></a>";
        string to   = "<a href=""></a>";
        string subject = Your request has been received";
        string body = "We got your request. Hang in there, help is on the way.";

        smtpClient.Send( from, to, subject, body );

The interesting bits are in the instantiation of the SmtpClient object. Also note the comment on SmptClient implementing IDisposable in .NET 4.0, but not in earlier versions of the framework. Since I am targeted the .NET 4.0 framework, I’ve treated that instantiation as resource acquisition and enclosed it in a using statement. 

This sample uses no configuration. Alternatively, you can configure these values in the <smtp> element of app.config.

Comments are closed.