Azure Communication Service - .NET Client with ConnectionString

Azure Communication Service - .NET Client with ConnectionString

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 connection string in your .NET project.

Be aware that the connection string should be used primarily with software that is not operated on Azure in a managed identity context. If you are on Azure, use the more secure variant via the Managed Identity! See Azure Communication Service - .NET Client with Managed Identity

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(myConnectionString);

// 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.ConnectionString);
    }

    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!; // [email protected]
}

public class CommunicationServiceOptions
{
    [Required]
    public string ConnectionString { get; set; } = null!; // endpoint=https://<your-communication-service>.<location>.communication.azure.com/;accesskey=abcxyz
}

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