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.

1using Azure.Communication.Email
2
3// create instance
4EmailClient mailClient = new(new Uri(yourEndpointAddress), new DefaultAzureCredential());
5
6// send mail
7EmailSendOperation emailSendOperation = await mailClient.SendAsync(
8    Azure.WaitUntil.Completed, fromAddress, toMailAddress, subject, htmlBody, plainTextContent: null, cancellationToken)
9    .ConfigureAwait(false);

The simple client class

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

 1public sealed class AzureCommunicationServiceEMailClient
 2{
 3    private readonly EmailClient _mailClient;
 4    private readonly EMailOptions _emailOptions;
 5    private readonly CommunicationServiceOptions _acsOptions;
 6
 7    public AzureCommunicationServiceEMailClient(
 8        IOptions<EMailOptions> emailOptions,
 9        IOptions<CommunicationServiceOptions> acsOptions)
10    {
11        _emailOptions = emailOptions.Value;
12        _acsOptions = acsOptions.Value;
13
14        _mailClient = new(_acsOptions.Endpoint);
15    }
16
17    public async Task Send(string toMailAddress, string subject, string htmlBody, CancellationToken ct)
18    {
19        string fromAddress = _emailOptions.FromAddress;
20
21        await _mailClient.SendAsync(
22            Azure.WaitUntil.Completed, fromAddress, toMailAddress, subject, htmlBody, plainTextContent: null, ct);
23    }
24}

The following two classes are used for the options:

 1public class EMailOptions
 2{
 3    [Required]
 4    [EmailAddress]
 5    public string FromAddress { get; set; } = null!;
 6}
 7
 8public class CommunicationServiceOptions
 9{
10    [Required]
11    public string Endpoint { get; set; } = null!; // https://<your-communication-service>.<region>.communication.azure.com
12}

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


Comments

Twitter Facebook LinkedIn WhatsApp