Karl Gjertsen

Architect, Developer, Speaker, Bad Golfer,
Raygun brand ambassador and creator of Infiniforms

Unit testing email code with Mail4Net

When it comes to unit testing your code, Mail4Net provides a great way to test your email sending code.

In my previous article, I showed sending an email with Mail4Net. If you are new to Mail4Net, then I would suggest you start with this article.

Using the fake client

The fake client stores emails that have been sent and they can then be retrieved so you can check your sending code.

Using the fake client is a simple matter of swapping the client used:

private void SendEmail_Clients()

  // Create mail message.
  var message = new System.Net.Mail.MailMessage();
  message.From = new MailAddress("me@mydomain.com");
  message.Subject = "Hello World";
  message.Body = "Here is an email";

  // Send email - Fake client.
  var fake = new Mail4Net.Client.FakeClient();


Once the fake client receives messages, you can call methods to check if any emails have been sent, check the number of emails sent and you can also retrieve the messages:

// Check if email has been sent.
var mailSent = fake.MailSent;

// Check how many emails have been sent.
var count = fake.Messages.Count();

You can also retrieve the MailMessage objects, either by an index or by stepping through them:

// Get a message by index.
var first = fake.Messages[0];
Console.WriteLine("To: {0}", first.To.ToString());
Console.WriteLine("Subject: {0}", first.Subject);

// Step through messages sent.
foreach (var msg in fake.Messages)
  Console.WriteLine("To: {0}", msg.To.ToString());
  Console.WriteLine("Subject: {0}", msg.Subject);

You can clear all of the messages received by calling the clear method:

// Clear sent emails.

You can find out more about Mail4Net at the Mail4Net website.


%d bloggers like this: