SMTP Emails in .NET: 1 Powerful library to Improve Email Delivery

email

Introduction

In this blog post, we’ll explore how to use the SMTP Email Service library that I recently created for .NET applications (github link) to send emails using the Simple Mail Transfer Protocol (SMTP). We’ll cover the key features of the library, show how to install and configure it in a .NET application, and provide examples of how to use it to send emails.

Features

The SMTP Email Service library provides the following features:

  • Supports sending plain text and HTML emails.
  • Supports sending emails to multiple recipients and adding CC and BCC recipients.
  • Provides fault tolerance using Polly library.

Installation

To install the SMTP Email Service library, run the following command in the Package Manager Console:

Install-Package Biplov.Email.Smtp

Alternatively, you can use the .NET CLI:

dotnet add package Biplov.Email.Smtp

Configuration

To use the SMTP Email Service library, you’ll need to configure it in your application’s service collection using the AddSmtpEmailService extension method. This method registers the SmtpEmailService with the required dependencies, including an IAsyncPolicy instance for handling timeouts and retrying failed attempts.

Here’s an example of how to configure the SMTP Email Service library in a .NET application’s Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<SmtpCredentials>(Configuration.GetSection("SmtpCredentials"));

    var asyncPolicy = Policy
        .TimeoutAsync(TimeSpan.FromSeconds(30))
        .WrapAsync(Policy
            .Handle<TimeoutException>()
            .WaitAndRetryAsync(
                retryCount: 3,
                sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))
            ));

    services.AddSmtpEmailService(asyncPolicy);
}

This example uses the Configure method of the IServiceCollection interface to configure the SmtpCredentials class from the app settings file. This is necessary to provide the SmtpCredentials object to the SmtpEmailService constructor using IOptions<SmtpCredentials>.

Sending Emails

Once the SMTP Email Service library is configured, you can use it to send emails using the IEmailService interface. Here’s an example of how to send an email using the SendAsync method of IEmailService:

var emailService = serviceProvider.GetRequiredService<IEmailService>();

var result = await emailService.SendAsync(
    "Hello World",
    "This is a test email from SmtpEmail",
    new List<string> { "recipient@example.com" },
    "sender@example.com"
);

result.Match(
    success => Console.WriteLine("Email sent successfully."),
    formatException => Console.WriteLine($"Email format exception: {formatException.Message}"),
    authenticationException => Console.WriteLine($"Authentication failed: {authenticationException.Message}"),
    smtpException => Console.WriteLine($"SMTP error: {smtpException.Message}"),
    timeoutException => Console.WriteLine($"SMTP connection timed out: {timeoutException.Message}"),
    exception => Console.WriteLine($"Unhandled exception: {exception.Message}")
);

This example sends a test email using the SendAsync method of IEmailService. The Match method is used to handle the different possible outcomes of the method call, including success, format exceptions, authentication exceptions, SMTP exceptions, timeouts, and unhandled exceptions.

Conclusion

The SMTP Email Service library provides an easy-to-use interface for sending emails with fault tolerance.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.