DEV Community

Alexandru Bucur
Alexandru Bucur

Posted on

The confusing way of sending emails in .NET Core and other goodies

Since I finally had some time to play more with C# I've encountered my next challenge when wanting to implement user registration with a confirmation email.

Even though the official documentation is clear on how to handle the one time code generation I didn't want to use Sendgrid but plain old SMTP authentication. Further more I don't agree with having the mail body as a string in my registration task.

Now, this is where things got complicated rather fast.
The tutorial says it includes System.Net.Mail and that has a SmtpClient but unfortunately the API is Obsolete.

Not all things are lost because It does recommend using MailKit but since Mailkit doesn't handle any kind of template management I started looking googling around on how people are sending emails in net.core in general.

I would like to give a shout-out to FluentEmail since it was almost what I wanted to have (minus the MailKit handler).

Without further ado you can access the current version in this github commit or check the commit directly

I've used the Options pattern to simplify the dependency injection handling, RazorLight for the template handling (Maybe somebody over at Microsoft can extract the official thing as a library), and implemented a simple sendEmailFromTemplateAsync method in my EmailsService.

I had to hack around RazorLight's CompileRenderAsync since sending an anonymous object to sendEmailFromTemplateAsync and passing that directly as the model in the CompileRenderAsync method somehow broke the variable parsing.
The workaround is making the messageData as an Dictionary and converting that into an object using ExpandoObject

var localMessageData = messageData.Aggregate(
    new ExpandoObject() as IDictionary<string, Object>,
    (a, p) => { a.Add(p.Key, p.Value); return a; }
Enter fullscreen mode Exit fullscreen mode

How are you guys handling emails in your applications ?

Top comments (1)

akashkava profile image
Akash Kava

I used to use Razor, but eventually world needs preview and WYSIWYG editor. So I switched to handlebars. JS Library can display preview of handlebars template to user before sending email. User can customize template easily. There are various template editors, such as which has excellent browser editor support. Slowly we are coming out of .NET Core and switching to NodeJS via NodeServices.