Here's a class for unit testing sending mail inspired by nDumbster:
http://ndumbster.sourceforge.net/default.html
and Phil Haack's article about unit testing a mail server:
http://haacked.com/archi...EmailFunctionality.aspx
I needed more than just a mocked out sendmail implementation. I needed to verify that I was sending an HTML formatted message. The ReceivedEmail object mirrors the important properties of System.Net.Mail.MailMessage.
I had a difficult time figuring out how to setup/start the server and finding the Mime object (am I shutting down the server correctly?). Perhaps this example could be included in the documentation so other users have a working example of the code.
Cheers,
Ron
Code:
/// <author>Ron Grabowski</author>
public sealed class TestSmtpServer : IDisposable
{
private readonly List<ReceivedEmail> receivedEmails = new List<ReceivedEmail>();
private SMTP_Server server;
public void Start(string host, int port)
{
if (server != null)
{
return;
}
server = new SMTP_Server();
server.BindInfo = new[] {new IPBindInfo(host, BindInfoProtocol.TCP, IPAddress.Loopback, port)}; // ???
server.MessageStoringCompleted += server_MessageStoringCompleted;
server.StartServer();
}
private void server_MessageStoringCompleted(object sender, MessageStoringCompleted_eArgs e)
{
lock (receivedEmails)
{
e.MessageStream.Seek(0, SeekOrigin.Begin);
receivedEmails.Add(new ReceivedEmail(Mime.Parse(e.MessageStream)));
}
}
public ReceivedEmail[] ReceivedEmails
{
get
{
lock (receivedEmails)
{
return receivedEmails.ToArray();
}
}
}
public void ClearReceivedEmails()
{
lock (receivedEmails)
{
receivedEmails.Clear();
}
}
public int ReceivedEmailsCount
{
get
{
lock (receivedEmails)
{
return receivedEmails.Count;
}
}
}
public void Stop()
{
if (server == null)
return;
Dispose(true);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (server != null)
{
server.Enabled = false;
server.StopServer();
server.Dispose();
}
}
}
public class ReceivedEmail
{
public string to;
public string from;
public string subject;
public string body;
public bool isBodyHtml;
public Mime rawEmail;
public ReceivedEmail(Mime mime)
{
this.rawEmail = mime;
}
public string To
{
get { return RawEmail.MainEntity.To.ToAddressListString(); }
}
public string From
{
get { return RawEmail.MainEntity.From.ToAddressListString(); }
}
public string Subject
{
get { return RawEmail.MainEntity.Subject; }
}
public string Body
{
get { return IsBodyHtml ? RawEmail.BodyHtml : RawEmail.BodyText; }
}
public bool IsBodyHtml
{
get { return RawEmail.MainEntity.ContentType == MediaType_enum.Text_html; }
}
public Mime RawEmail
{
get { return rawEmail; }
}
}
}