How to Send HTML E-mail from an ASP.NET MVC Controller

As I argued about a year ago, any **modern piece of software needs **to send e-mail. It needs to connect, and reach its users. Back then I showed how to send templated HTML e-mail, using the little known MailDefinition class in C#.

Today, there’s an even better approach. The main problem with the old solution, was that the templates were plain, old, flat and boring HTML templates. Any sort of dynamic content, were limited to what a simple replace could do.

The better approach that I’m using now, is the awesome ActionMailer.NET package. It’s right there within Visual Studio, if you have Nuget – which I’m sure you do.

Why is it better?

ActionMailer.NET is better, first of all because the templates for your e-mails are just regular ASP.NET MVC views. That means you can strongly type those view and supply it with a model. All the stuff you can do in an ASP.NET MVC View (Razor or WebForms – your choice) – you can now send via E-mail.

It’s very easy to use

You simply start by creating a new Controller in your ASP.NET MVC web application that will take care of sending all the e-mails. Along with the controller, you add a folder for the views.

publicclass MailController : MailerBase { public EmailResult VerificationEmail(User model) { To.Add(model.EmailAddress); From = "Martin Normark [email protected]"; Subject = "Welcome to My Blog!";

return Email("VerificationEmail", model); } }

Notice how you can set the from name, as well as the e-mail address. Neat stuff. If you want to do something just before or after an e-mail is sent, you can play around with the OnMailSending and OnMailSent by overriding the default implementation.

protectedoverridevoid OnMailSending(MailSendingContext context) { base.OnMailSending(context); } protectedoverridevoid OnMailSent(System.Net.Mail.MailMessage mail) { base.OnMailSent(mail); }

Maybe you want to save the e-mail in your database for future reference, logging etc.

One thing I’ll do one day, is combine this with the premailer Ruby project, that optimizes your HTML e-mails for rendering in e-mail clients, by moving your CSS inline.