An interesting problem arose when I started using this (otherwise wonderful) library.
What I was getting was intermittent test failures, while running acceptance tests against a IIS hosted website that sent emails using System.Net.Mail.SmtpClient. I finally tracked it down to this: SmtpClient normally pools connections to SMTP servers and close them in its own time, and admittedly this seems to be a good idea for a long-running website.
However, it plays havoc with the EmbeddedSmtpServer because it is started and stopped for every test run, and because the IIS website outlasts the test run, the pooled connection is terminated. When the website goes to send another email (say, on the next test run), it breaks, saying that the connection has been terminated - that's the connection to the EmbeddedSmtpServer in the previous test run.
It seems there are three approaches:
- The server can tell the client that its disconnecting, closing the connection gracefully. The SMTP spec describes a 421 response, which a server can use to terminate the connection. The idea is that the client would read their TCP connection before attempting more interaction with the server, however this doesn't seem to work for SmtpClient.
- Use the .Net 4.0 SmtpClient, Disposing after each sent email. This could be done in an automated test environment, leaving the connection pooling to production.
- Leave the SMTP server going for as long as the connection pools seem to survive. Connection pools seem to live (AFAIK) for less than a minute, so as long as two test runs are at least a minute apart then it seems to be ok. Not exactly fool proof.
The first seemed promising but didn't seem to work, neither of the other two are particularly good solutions.
Nevertheless, I thought I'd document this here for future reference.
Any ideas, thoughts, advise?