Azure Communication Service - .NET Client with Managed Identity

Azure Communication Service - .NET Client with Managed Identity

The Azure Communication Service is a fairly new but already popular service for sending emails at scale. In this article, I would like to show you how you can use the service via a Azure Managed Identity in your .NET project.

Be aware that the Managed Identity only works on Azure. If you want to use the Azure Communication Service outside of Azure, you have to use the connection string to initialize your client. See Azure Communication Service - .NET Client with ConnectionString

The email client

To be able to use the Azure Communication Service in your .NET project, you need the official NuGet package Azure.Communication.Email. With the help of this package and the corresponding using, the client can be initialised directly.

using Azure.Communication.Email

// create instance
EmailClient mailClient = new(new Uri(yourEndpointAddress), new DefaultAzureCredential());

// send mail
EmailSendOperation emailSendOperation = await mailClient.SendAsync(
    Azure.WaitUntil.Completed, fromAddress, toMailAddress, subject, htmlBody, plainTextContent: null, cancellationToken)
    .ConfigureAwait(false);

The simple client class

A very simple class - without error handling, without logging, without retry can look like this:

public sealed class AzureCommunicationServiceEMailClient
{
    private readonly EmailClient _mailClient;
    private readonly EMailOptions _emailOptions;
    private readonly CommunicationServiceOptions _acsOptions;

    public AzureCommunicationServiceEMailClient(
        IOptions<EMailOptions> emailOptions,
        IOptions<CommunicationServiceOptions> acsOptions)
    {
        _emailOptions = emailOptions.Value;
        _acsOptions = acsOptions.Value;

        _mailClient = new(_acsOptions.Endpoint);
    }

    public async Task Send(string toMailAddress, string subject, string htmlBody, CancellationToken ct)
    {
        string fromAddress = _emailOptions.FromAddress;

        await _mailClient.SendAsync(
            Azure.WaitUntil.Completed, fromAddress, toMailAddress, subject, htmlBody, plainTextContent: null, ct);
    }
}

The following two classes are used for the options:

public class EMailOptions
{
    [Required]
    [EmailAddress]
    public string FromAddress { get; set; } = null!;
}

public class CommunicationServiceOptions
{
    [Required]
    public string Endpoint { get; set; } = null!; // https://<your-communication-service>.<region>.communication.azure.com
}

As the EmailClient itself is thread-safe, the entire AzureCommunicationServiceEMailClient class can be used in a singleton scenario.