Tuesday 23 April 2013

In-Memory POP3 Server in C#


Today I had a requirement where we needed to download a message from an email server via POP3 and convert it to another message format to be used in a CMS.

As anyone that knows me testing is very important so I wanted to find a way to create an in-memory POP3 server. The reason for this was I wanted a way to test different kinds of messages that needed to be saved in the CMS and not rely on an actual physical server. So after searching for a while I realised that there wasn't much out there so I decided to write my own.


I created a gist that shows you the specs that I wrote. An example spec looks like this:

It("should get a message with OpenPop.NET", () =>
        using (var client = new OpenPop.Pop3.Pop3Client()) {
            client.Connect("localhost", 110, false);
            client.Authenticate("test", "test");

            var message = client.GetMessage(1).ToMailMessage();

The email message that I used to test looks like the following:

Return-Path: <dzs@iname.com>
Received: from iname.com (localhost [])
        by localhost.localdomain (8.8.5/8.8.5) with ESMTP id RAA01110
        for <dzs@localhost>; Sat, 3 Jan 1998 17:46:55 -0800
Sender: dzs@localhost.localdomain
Message-ID: <34AEEA0E.71EA3BCC@iname.com>
Date: Sat, 03 Jan 1998 17:46:55 -0800
From: Doug Steinwand <dzs@iname.com>
To: dzs@localhost.localdomain
Subject: Test Message

Here's the body of my test message

 - Doug

The actual implementation is in the following gist. The library that I chose to use was LumiSoft.Net as it already had an implementation of a POP3 server (it just needed to be extended).

The interesting part is that for some reason the library AE.Net.Mail (which was the one we wanted to use at work) does not work. I get the following error:

1) should get a message with AE.Net.Mail
   Failure/Error: System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

So I will probably be replacing it for one of the other client libraries.

This is a quick way to enable a POP3 server in memory and I hope this helps someone else in a similar position.

No comments:

Post a Comment