How to send email in 5min with FluentEmail?

Aug 28 2023

 
 

Thank you!

 
 

We just passed 6000 of you really wonderful people who follow me here and send content. I try to ensure that each newsletter issue is of sufficient quality to provide you with enough value.

 

I would like you to write me testimonials that would help me and other people who would come to the Newsletter. At the end of the completed testimonials, as a sign of gratitude, I will give you something valuable.

 

Write it here.

 

Thank you!

 
 

Background

 
 

New user registered on your app?
The verification code should be sent to his email.

 

User forgot password?

 

And a thousand more such examples. Production applications today cannot live without some kind of email sending. That's why we need something easily and quickly configurable for sending emails.

 

Introducing FluentEmail.

 

 

Let's dive in.

 
 

Quick Configuration

 
 

The first thing that is necessary is to add a new package from the NuGet package manager.

dotnet add package FluentEmail.Core
dotnet add package FluentEmail.Smtp

 

Now you can use the library.

 

How?

 
 

Basic Usage

 
 

To construct and send an email you just keep building up the fluent methods on the IEmail class (comes from FluentEmail). When you are ready to send, call SendAsync ().

var email = await Email
    .From("stefan@gmail.com")
    .To("milan@gmail.com", "Milan")
    .Subject("Hi Milan!")
    .Body("Works!")
    .SendAsync();

 

There are the most common methods available on the email object:

 

.To (string emailAddress) - add recipients
.SetFrom (string emailAddress) - change the sender address.
.CC/BCC (string emailAddress) - add CC or BCC
.Subject (string subject) - set the subject
.Body (string body) - set the message body (without templating)
.Attach (Attachment attachment) - add attachments
.UsingTemplate (string template, T model, bool isHtml = true) - set a template, keep reading for more templating information
.SendAsync () - send the email using the configured sender

 
 

Better way?

Dependency Injection

 
 

The best way to use FluentEmail is to configure your sender and template choices with dependency injection.

 

Let's configure it in Program.cs class:

builder.Services.
       .AddFluentEmail("from@gmail.com")
       .AddRazorRenderer()
       .AddSmtpSender("localhost", 25);

 

What I did here?

 

.AddFluentEmail () - sets up FluentEmail with a default SendFrom address.
AddSmtpSender () - configures the SmtpSender provider (ISender interface).
AddRazorRenderer () - sets the RazorRenderer provider - templating support (ITemplateRenderer interface).

 

Using dependency injection will make a couple of interfaces available to your code. See the example below for sending email with the configured services:

public class EmailService : IEmailService
{
    private readonly IFluentEmail _fluentEmail;

    public EmailService(IFluentEmail fluentEmail)
    {
        _fluentEmail = fluentEmail;
    }

    public async Task Send()
    {
        await _fluentEmail
                .To("test@gmail.com")
                .Subject("Test email")
                .Body("Test body")
                .SendAsync();
    }
}

 
 

Razor Email Templates

 
 

We want the emails we send to have the same template and style. Especially if we send a newsletter, like this one for example :D

 


dotnet add package FluentEmail.Razor

 

The RazorRenderer supports any valid Razor code .

 

Let's see the example:

//configure the Razor Renderer
builder.Services
       .AddFluentEmail("from@gmail.com")
       //pass in a type in the assemble with embedded tempaltes
       .AddRazorRenderer(typeof(Program))

//In your template code include a layout file
//the template could be sourced from file/embedded if that is configured
var template = @"
    @{Layout = ""./Shared/_Layout.cshtml""; }

    Hi @Model.Name here is a list @foreach(var i in Model.Numbers) { @i }";

var model = new { Name = "Stefan", Numbers = new [] { 1, 2, 3} };

var email = new Email()
      .To("test@gmail.com")
      .Subject("Razor template example")
      .UsingTemplate(template, model);

 

Some other templates?

 

There is a support for Liquid Templates , also. The Liquid Templates are a more restricted templating language created by Shopify. They are more lightweight than Razor templates as well as safer and simpler for end users to create. Properties on the model are made available as Liquid properties in the template.

 
 

Email Senders

 
 

 

To use a sender include the provider and configure it as part of dependency injection. 

 

The following senders are available as core libraries:

 

- SMTP Sender
- Mailgun Sender
- SendGrid Sender
- MimeKit Sender

 

Let's see how it's easy to configure it with SendGrid for example.

 

First, you need to add another package from the NuGet:

dotnet add package FluentEmail.SendGrid

 

And lastly, you just need to configure it in Program.cs:

builder.Services
       .AddFluentEmail("from@gmail.com")
       .AddSendGridSender("apikey");

 

And that's it. You have integrated it.

 

This is so perfect!

 
 

What next?

 
 

I showed you how with the help of the FluentEmail library it is possible to send an email in 5 minutes. It can be easily integrated with various Email Senders, as well as being able to include various renders.

 

You can go to the project's GitHub repository and get acquainted with the details.

 

That's all from me today.

Join 10,950+ subscribers to improve your .NET Knowledge.

There are 3 ways I can help you:

Design Patterns Simplified ebook

Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.


Sponsorship

Promote yourself to 10,950+ subscribers by sponsoring this newsletter.


Join .NET Pro Weekly Newsletter

Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.


Subscribe to
.NET Pro Weekly

Subscribe to the .NET Pro Weekly and be among the 10,950+ subscribers gaining practical tips and resources to enhance your .NET expertise.