Quickstart: How to send an email using Azure Communication Service

Important

This feature of Azure Communication Services is currently in public preview. Preview APIs and SDKs are provided without a service-level agreement, and are not recommended for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.

In this quick start, you'll learn about how to send email using our Email SDKs.

Get started with Azure Communication Services by using the Communication Services C# Email client library to send Email messages.

Completing this quick start incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

Prerequisite check

  • In a terminal or command window, run the dotnet command to check that the .NET client library is installed.
  • To view the subdomains associated with your Email Communication Services resource, sign in to the Azure portal, locate your Email Communication Services resource and open the Provision domains tab from the left navigation pane.

Setting up

Create a new C# application

In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name EmailQuickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

dotnet new console -o EmailQuickstart

Change your directory to the newly created app folder and use the dotnet build command to compile your application.

cd EmailQuickstart
dotnet build

Install the package

While still in the application directory, install the Azure Communication Services Email client library for .NET package by using the dotnet add package command.

dotnet add package Azure.Communication.Email --prerelease

Open Program.cs and replace the existing code with the following to add using directives for including the Azure.Communication namespace and a starting point for execution for your program.


using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using Azure;
using Azure.Communication.Email;
using Azure.Communication.Email.Models;

namespace SendEmail
{
  internal class Program
  {
      static async Task Main(string[] args)
      {
          
      }
  }
}

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Email Client library for C#.

Name Description
EmailAddress This class contains an email address and an option for a display name.
EmailAttachment This class creates an email attachment by accepting a unique ID, email attachment type, and a string of content bytes.
EmailClient This class is needed for all email functionality. You instantiate it with your connection string and use it to send email messages.
EmailClientOptions This class can be added to the EmailClient instantiation to target a specific API version.
EmailContent This class contains the subject and the body of the email message. The importance can also be set within the EmailContent class.
EmailCustomHeader This class allows for the addition of a name and value pair for a custom header.
EmailMessage This class combines the sender, content, and recipients. Custom headers, attachments, and reply-to email addresses can optionally be added, as well.
EmailRecipients This class holds lists of EmailAddress objects for recipients of the email message, including optional lists for CC & BCC recipients.
SendStatusResult This class holds lists of status of the email message delivery.

Authenticate the client

Open Program.cs in a text editor and replace the body of the Main method with code to initialize an EmailClient with your connection string. The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. Learn how to manage your resource's connection string.

// This code demonstrates how to fetch your connection string
// from an environment variable.
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
EmailClient emailClient = new EmailClient(connectionString);

Send an email message

To send an Email message, you need to

  • Construct the email content and body using EmailContent
  • Add Recipients
  • Construct your email message with your Sender information you get your MailFrom address from your verified domain.
  • Include your Email Content and Recipients and include attachments if any
  • Calling the Send method. Add this code to the end of Main method in Program.cs:

Replace with your domain details and modify the content, recipient details as required


//Replace with your domain and modify the content, recipient details as required

EmailContent emailContent = new EmailContent("Welcome to Azure Communication Service Email APIs.");
emailContent.PlainText = "This email message is sent from Azure Communication Service Email using .NET SDK.";
List<EmailAddress> emailAddresses = new List<EmailAddress> { new EmailAddress("emailalias@contoso.com") { DisplayName = "Friendly Display Name" }};
EmailRecipients emailRecipients = new EmailRecipients(emailAddresses);
EmailMessage emailMessage = new EmailMessage("donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net", emailContent, emailRecipients);
SendEmailResult emailResult = emailClient.Send(emailMessage,CancellationToken.None);

Getting MessageId to track email delivery

To track the status of email delivery, you need to get the MessageId back from response and track the status. If there's no MessageId retry the request.

 Console.WriteLine($"MessageId = {emailResult.MessageId}");

Getting status on email delivery

To get the delivery status of email call GetMessageStatus API with MessageId

Response<SendStatusResult> messageStatus = null;
messageStatus = emailClient.GetSendStatus(emailResult.MessageId);
Console.WriteLine($"MessageStatus = {messageStatus.Value.Status}");
TimeSpan duration = TimeSpan.FromMinutes(3);
long start = DateTime.Now.Ticks;
do
{
    messageStatus = emailClient.GetSendStatus(emailResult.MessageId);
    if (messageStatus.Value.Status != SendStatus.Queued)
    {
        Console.WriteLine($"MessageStatus = {messageStatus.Value.Status}");
        break;
    }
    Thread.Sleep(10000);
    Console.WriteLine($"...");

} while (DateTime.Now.Ticks - start < duration.Ticks);
Status Name Description
None An email with this messageId couldn't be found.
Queued The email has been placed in the queue for delivery.
OutForDelivery The email is currently en route to its recipient(s).
InternalError An error occurred internally during the delivery of this message. Please try again.
Dropped The email message was dropped before the delivery could be successfully completed.
InvalidEmailAddress The sender and/or recipient email address(es) is/are not valid.
InvalidAttachments The content bytes string for the attachment isn't valid.
InvalidSenderDomain The sender's email address domain isn't valid.

Run the code

Run the application from your application directory with the dotnet run command.

dotnet run

Sample code

You can download the sample app from GitHub

Get started with Azure Communication Services by using the Communication Services JS Email client library to send Email messages.

Completing this quick start incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

Prerequisite check

  • In a terminal or command window, run node --version to check that Node.js is installed.
  • To view the domains verified with your Email Communication Services resource, sign in to the Azure portal, locate your Email Communication Services resource and open the Provision domains tab from the left navigation pane.

Setting up

Create a new Node.js Application

First, open your terminal or command window, create a new directory for your app, and navigate to it.

mkdir email-quickstart && cd email-quickstart

Run npm init -y to create a package.json file with default settings.

npm init -y

Use a text editor to create a file called send-email.js in the project root directory. Change the "main" property in package.json to "send-email.js". You'll add all the source code for this quickstart to this file in the following sections.

Install the package

Use the npm install command to install the Azure Communication Services Email client library for JavaScript.

npm install @azure/communication-email --save

The --save option lists the library as a dependency in your package.json file.

Object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Email Client library for JavaScript.

Name Description
EmailAddress This interface contains an email address and an option for a display name.
EmailAttachment This interface creates an email attachment by accepting a unique ID, email attachment type, and a string of content bytes.
EmailClient This class is needed for all email functionality. You instantiate it with your connection string and use it to send email messages.
EmailClientOptions This interface can be added to the EmailClient instantiation to target a specific API version.
EmailContent This interface contains the subject, plaintext, and html of the email message.
EmailCustomHeader This interface allows for the addition of a name and value pair for a custom header.
EmailMessage This interface combines the sender, content, and recipients. Custom headers, importance, attachments, and reply-to email addresses can optionally be added, as well.
EmailRecipients This interface holds lists of EmailAddress objects for recipients of the email message, including optional lists for CC & BCC recipients.
SendStatusResult This interface holds the messageId and status of the email message delivery.

Authenticate the client

Import the EmailClient from the client library and instantiate it with your connection string.

The code below retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING using the dotenv package. Use the npm install command to install the dotenv package. Learn how to manage your resource's connection string.

npm install dotenv

Add the following code to send-email.js:

const { EmailClient } = require("@azure/communication-email");
require("dotenv").config();

// This code demonstrates how to fetch your connection string
// from an environment variable.
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];

Send an email message

To send an Email message, you need to

  • Construct the email content and body using EmailContent
  • Add Recipients
  • Construct your email message with your Sender information you get your MailFrom address from your verified domain.
  • Include your Email Content and Recipients and include attachments if any
  • Calling the send method:

Replace with your domain details and modify the content, recipient details as required


async function main() {
  try {
    var client = new EmailClient(connectionString);
    //send mail
    const emailMessage = {
      sender: "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>",
      content: {
        subject: "Welcome to Azure Communication Service Email.",
        plainText: "<This email message is sent from Azure Communication Service Email using JS SDK.>"
      },
      recipients: {
        to: [
          {
            email: "<emailalias@emaildomain.com>",
          },
        ],
      },
    };
    var response = await client.send(emailMessage);
  } catch (e) {
    console.log(e);
  }
}
main();

Getting MessageId to track email delivery

To track the status of email delivery, you need to get the MessageId back from response and track the status. If there's no MessageId, retry the request.

  const messageId = response.messageId;
  if (messageId === null) {
    console.log("Message Id not found.");
    return;
  }
   

Getting status on email delivery

To get the delivery status of email call GetMessageStatus API with MessageId

  // check mail status, wait for 5 seconds, check for 60 seconds.
  let counter = 0;
  const statusInterval = setInterval(async function () {
    counter++;
    try {
      const response = await client.getSendStatus(messageId);
      if (response) {
        console.log(`Email status for ${messageId}: ${response.status}`);
        if (response.status.toLowerCase() !== "queued" || counter > 12) {
          clearInterval(statusInterval);
        }
      }
    } catch (e) {
      console.log(e);
    }
  }, 5000);

Status Name Description
Queued The email has been placed in the queue for delivery.
OutForDelivery The email is currently en route to its recipient(s).
Dropped The email message was dropped before the delivery could be successfully completed.

Run the code

use the node command to run the code you added to the send-email.js file.

node ./send-email.js

Sample code

You can download the sample app from GitHub

Troubleshooting

To troubleshoot issues related to email delivery, you can get status of the email delivery to capture delivery details.

Clean up resources

If you want to clean up and remove a Communication Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it. Learn more about cleaning up resources.

Next steps

In this quick start, you learned how to send emails using Azure Communication Services.

You may also want to: