FluentEmail: Sending Emails in .NET Projects

Sending emails in applications is a common and crucial feature in many types of projects. Whether it’s to send a simple welcome email, a system alert, or an event notification, choosing the right tool to handle this process can significantly impact code readability and maintainability. FluentEmail is a library that aims to simplify email sending with a fluent, modern, and highly configurable syntax in .NET projects.

In this article, we’ll explore what FluentEmail is, how to configure it, use it with templates and integrations, and discuss best practices for its use in different project scenarios.

Installation and Initial Configuration

To start using FluentEmail in your .NET project, you need to install a few NuGet packages. Open the Package Manager Console in Visual Studio or use the .NET CLI to install the required packages:

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

				
			

These packages include the core library and support for sending via SMTP. If you’re using another sending service like SendGrid or Mailgun, you’ll need to install the corresponding additional packages. In our example, we’ll use SendGrid:

				
					dotnet add package FluentEmail.SendGrid

				
			

With these packages installed, we can configure FluentEmail in the project.

Configuring FluentEmail in Program.cs

Once the packages are installed, it’s time to configure FluentEmail. In ASP.NET Core, we can use Dependency Injection to set up and use FluentEmail in our services.

In the Program.cs file, add the FluentEmail configuration as follows:

				
					builder.Services
    .AddFluentEmail("user@domain.com")
    .AddSmtpSender(
        "smtp.mailersend.net",
        2525,
        "user@domain.com",
        "your_api_key_here"
    );

				
			

Here, we use the AddFluentEmail method to add the FluentEmail service to the ASP.NET Core dependency injection container. This method sets the sender’s email address that will be used for all outgoing emails.

After configuring the sender, we add the AddSmtpSender method, which is responsible for defining the SMTP email sending settings. This method sets up the server that FluentEmail will use to send messages.

  • "smtp.mailersend.net": The SMTP server used to send the emails. MailerSend provides this address to enable communication with the email server.

  • 2525: The port used for SMTP communication. Port 2525 is often chosen as an alternative to the default port 25, which can be blocked.

  • "user@domain.com": The username for SMTP server authentication, usually an email or subdomain associated with your account.

  • "your_api_key_here": The password or API key used for authentication.

To find these settings, just go to the email area, click on “Domains”, access or create the desired domain, and select the SMTP option. The settings will be displayed for you like this.

Now Let’s Implement the Sending Code

				
					[ApiController]
[Route("[controller]")]
public class EmailNotificationController : ControllerBase
{
    private readonly IFluentEmail _fluentEmail;

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

    public async Task<ActionResult> SendNotificationEmail(string email, string subject, string message)
    {
        await _fluentEmail
            .To(email)
            .Subject(subject)
            .Body(message)
            .SendAsync();

        return Ok();
    }
}

				
			

In this code, we receive the email parameters directly in the endpoint: the email recipient is passed to the To field, the subject defines the email subject, and the body contains the email content. Finally, the SendAsync method is called to send the message asynchronously. This ensures that the sending process does not block the application’s execution.

Best Practices

Here are some best practices to follow when using FluentEmail to send emails in .NET projects:

  • Asynchronous Execution: Always use SendAsync() to send emails asynchronously and avoid blocking the application flow.

  • Code Maintenance: Organize the email configuration and sending logic in a separate service (such as an EmailService), following the separation of concerns principle.

  • Security: Never store sensitive information like SMTP credentials or SendGrid API keys directly in the code. Use appsettings.json or environment variables to securely store this information. In our example, we used direct values in code only for didactic purposes.

Conclusion

In this article, we covered how to integrate email sending in .NET applications using the FluentEmail library. The proposed solution simplifies message configuration with a fluent and asynchronous approach, optimizing the process and ensuring greater code clarity. The flexibility provided by integration with Dependency Injection and SMTP server support makes FluentEmail an excellent choice for developers seeking a practical and efficient way to send emails without the complexity of traditional methods. This approach enables sending notifications and other messages in a simple and scalable way in .NET projects.