How to test email sending?

Nearly every web application these days sends some notifications to its users.

Many times before, I came across people who said that it’s not possible to test such things.
Well, they are wrong!

There is a very cool project on sourceforge called nDumbster:
http://ndumbster.sourceforge.net

nDumbster is a simple fake SMTP server designed especially to enable unit testing.

[TestFixture]
public class SmtpClientTest
{
    private const int _port = 25;
    private SimpleSmtpServer _smtpServer;

    [SetUp]
    public void SetUp()
    {
        _smtpServer = SimpleSmtpServer.Start(_port);
    }

    [TearDown]
    public void TearDown()
    {
        _smtpServer.Stop();
    }

    [Test]
    public void SendMessage_SendsMessage()
    {
        Mail.Text("Some tex")
            .Subject("Some subject")
            .From(new MailBox("alice@mail.com", "Alice"))
            .To(new MailBox("bob@mail.com", "Bob"))
            .UsingNewSmtp()
            .Server("localhost")
            .OnPort(_port)
            .Send();

        Assert.AreEqual(1, _smtpServer.ReceivedEmailCount);
        SmtpMessage mail = _smtpServer.ReceivedEmail[0];
        Assert.AreEqual(""Alice" <alice@mail.com>", mail.Headers["From"]);
        Assert.AreEqual(""Bob" <bob@mail.com>", mail.Headers["To"]);
        Assert.AreEqual("Some subject", mail.Headers["Subject"]);
        Assert.AreEqual("Some text", mail.Body);
    }
};

Tags:  

Questions?

Consider using our Q&A forum for asking questions.