Fluent Email Now Supporting Razor Syntax For Templates
30 Apr 2011A while back I wrote Fluent Email, a little .NET wrapper for sending emails with System.Net.Mail using a fluent interface. After relentless requests (there was at least 2) to publish the library on NuGet.org I eventually caved in. You can add Fluent Email to your project using Nuget’s built in library package manager or the following package console command.
The library is pretty simple buts makes the code for sending emails easy to use and read.
var email = Email .From("[email protected]") .To("[email protected]", "bob") .Subject("hows it going bob") .Body("yo dawg, sup?"); //send normally email.Send(); //send asynchronously email.SendAsync((sender, e) => { Console.WriteLine("Email Sent"); });
There are a few other methods not shown here that work in a similar way for adding the usual email suspects such as CC, BCC and ReplyTo.
I had also been playing around with some form of templating when I came across RazorEngine. RazorEngine is an awesome library that brings the razor syntax (from MVC3) to other applications. In Fluent Email we use RazorEngine to make email templates as simple as this:
var template = "Dear @Model.Name, You are totally @Model.Compliment."; var email = Email .From("[email protected]") .To("[email protected]") .Subject("woo nuget") .UsingTemplate(template, new { Name = "Luke", Compliment = "Awesome" });
This will set the body of the email to the rendered template “Dear Luke, You are totally Awesome." and can be sent the same way as the first example. The UsingTemplate method uses generics so you can pass in a specific type or just use an anonymous object like in the example. If you prefer to use a seperate file for your template there is a method called UsingTemplateFromFile to handle that. Since RazorEngine supports everything you would expect from the Razor view engine so does Fluent Email!
If you want to take a look at the code it is hosted on Github at lukencode/fluentemail otherwise just grab the NuGet package.