Recently I found a nuget package that allows me to use MVC Views and Layouts to define how my emails should look like, in a similar way as how mailer works in Ruby on Rails.
This article will show you how I integrated it into my online weekly planner WeekPlan.
1. Set up of the package (5 mins)
I first run the following two commands in my package manager console:
The second command generates the files I will need to customize MvcMailer behaviour and the view files for each email.
Finally, we need to set up our Web.Config:
Because I need a different configuration on production, I used the Configuration Transforms technique:
2. Setting up a new email to send (10 min)
Let’s check out how to write the method that will build the Invitation email:
Pretty straightforward. We build a standard MailMessage and call the PopulateBody method to call MVCMailer magic.
This is how my view file looks like:
The neat thing about MVCMailer is that it allows to set the HTML view and the Text view too (this is why I used the –WithText parameter when calling the scaffolder:
3. Send an email
In my controller, I need to call the Invitation method and use the extension method Send (given by MVCMailer) to send the email:
I have a base Controller class where I added the Mailer property:
If I test my code, I get a new file in my drop folder:
And if I open it in Outlook, I get the result I expected:
Nice isn’t it?