Fluent Email Now Supporting Razor Syntax For Templates

See an updated (2018) example of sending in .NET core email using FluentEmail.

A 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.

PM> Install-Package fluent-email

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.

👋 Are you an 🇦🇺 Australian developer or IT professional? Go check out my site Australian Technology Jobs - a Premium developer and IT job board and find awesome Australian dev jobs (and people).
Questions or comments? Follow me on twitter!
Follow @lukencode