A Simple SMTP Server Mock for .NET

A SMTP server mock is basically a fake SMTP server which can be used for unit testing of applications which send email messages. It acts as a real smtp server, except that  the incoming messages are locally stored and not actually delivered.  This can be quite usefull if you are using real data for testing.;-) 

1: [Test]

2: public void MailTest

3: {

4: SmtpMock smtpServerMock = new SmtpMock ;

5: smtpServerMock.Start;

6: System.Web.Mail.SmtpMail.SmtpServer = "localhost";

7: System.Web.Mail.SmtpMail.Send("somebody@foo.com", "everybody@bar.com", "This is the subject", "This is the body.");

8: smtpServerMock.Stop ;

9:  

10: Assert.AreEqual (1, smtpServerMock.Sessions.Count);

11: SmtpSession session = (SmtpSession) smtpServerMock.Sessions[0];

12: Assert.IsTrue (session.SessionProtocol.IndexOf("somebody@foo.com") > 0 );

13: Assert.IsTrue (session.SessionProtocol.IndexOf("everybody@bar.com") > 0 );

14: Assert.IsTrue (session.SessionProtocol.IndexOf("This is the subject") > 0 );

15: Assert.IsTrue (session.SessionProtocol.IndexOf("This is the body.") > 0 );

16:  

17: }

Example: Unit-Test with SMTP-Server Mock

As I couldn't find a.NET implementation (take a look at dumbster for java version), I decided to write one myself. The implementation is very simple as it only opens a listener at port 25 and responds to pretty much anything with 250 OK. ;-) . The recieved emails are stored in SessionProtocol (see example).

[1] Dumbster - Fake SMTP Server for Java [2]

This article is part of the GWB Archives. Original Author: Igor Milovanovic

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.