// thinkbeforecoding


2011-01-21T13:45:00 / jeremie chassaing

I’ve been posting a sample SmtpListener on my repository a few days ago.

It’s infrastructure stuff.. what does it have to do with what I’m usually talking about here ?


It’s about Reactive Programming.


Sometimes you have to integrate with legacy systems that’ll send you things through email.

Ok, I know, it kind of sucks as an integration mechanism, but still… you have to do this way.


The usual way to receive email in an application is to set a mailbox on a mail server (think Exchange), and pull mailboxes periodically to see if there’s something new there.


There are two bad things here :

  • People tend to use their enterprise mail server for this. The mail sever is often vital for your business and screwing it up with a bug can have a big impact on your organization.
  • Email are pushed to you.. why would you pull it. You can push it directly on your service bus !

So, I prototyped a small smtp listener that could easily be integrated with whatever you want.


You need to add a MX entry in your dns zone configuration so that other servers find it, and get a valid certificate if you want to use secured TLS connections (I’ve disabled certificated verification for demo purpose).


But as you can see, the code is very simple since the .Net framework has already what’s needed.


The TcpListener is used to receive connections that’ll provide a TcpClient with underlying streams.

The SslStream class is used to encapsulate tcp streams to add Ssl encryption.

I’m using the reactive framework to convert the Begin/EndAcceptTcpClient methods to an Observable to avoid writing the accept loop myself.


Then implementation of the protocol is very easy, you can find an overview and sample on wikipedia.

The RFCs can easily be found :

RFC 5321: Simple Mail Transfer Protocol

RFC 3207: SMTP Service Extension for Secure SMTP over Transport Layer Security


Of course you can use it freely, and propose changes to make it better since it’s not attack proof.

This code is not resistant to known potential SMTP attacks, including dangling connections, long lines etc..