
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.
1using Azure.Communication.Email
2
3// create instance
4EmailClient mailClient = new(myConnectionString);
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.ConnectionString);
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!; // [email protected]
6}
7
8public class CommunicationServiceOptions
9{
10 [Required]
11 public string ConnectionString { get; set; } = null!; // endpoint=https://<your-communication-service>.<location>.communication.azure.com/;accesskey=abcxyz
12}
As the EmailClient itself is thread-safe, the entire AzureCommunicationServiceEMailClient class can be used in a singleton scenario.

Comments