Quickstart: How to send an email using Azure Communication Service

Important

This feature of Azure Communication Services is currently in preview.

Preview APIs and SDKs are provided without a service-level agreement. We recommend that you don't use them for production workloads. Some features might not be supported, or they might have constrained capabilities.

For more information, review 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 Azure CLI communication extension 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 az --version command to check that Azure CLI and the communication extension are 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

Add the extension

Add the Azure Communication Services extension for Azure CLI by using the az extension command.

az extension add --name communication

Sign in to Azure CLI

You need to sign in to Azure CLI. You can sign in running the az login command from the terminal and providing your credentials.

Store your connection string in an environment variable

You can configure the AZURE_COMMUNICATION_CONNECTION_STRING environment variable to use Azure CLI keys operations without having to use --connection_string to pass in the connection string. To configure an environment variable, open a console window and select your operating system from the below tabs. Replace <connectionString> with your actual connection string.

setx AZURE_COMMUNICATION_STRING "<yourConnectionString>"

After you add the environment variable, you may need to restart any running programs that will need to read the environment variable, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.

Send an email message

az communication email send
	--connection-string "yourConnectionString"
	--sender "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>"
	--to "<emailalias@emaildomain.com>"
	--subject "Welcome to Azure Communication Services Email" --text "This email message is sent from Azure Communication Services Email using Azure CLI." 

Make these replacements in the code:

  • Replace <yourConnectionString> with your connection string.
  • Replace <emailalias@emaildomain.com> with the email address you would like to send a message to.
  • Replace <donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net> with the MailFrom address of your verified domain.

To track the status of the email delivery, you need the messageId from the response.

Optional parameters

The following optional parameters are available in Azure CLI.

  • --html can be used instead of --text for html email body.

  • --importance sets the importance type for the email. Known values are: high, normal, and low. Default is normal.

  • --cc sets carbon copy email addresses.

  • --bcc sets blind carbon copy email addresses.

  • --reply-to sets Reply-To email address.

  • --disable-tracking indicates whether user engagement tracking should be disabled for this request.

  • --attachments sets the list of email attachments.

  • --attachment-types sets the list of email attachment types, in the same order of attachments.

Also, you can use a list of recipients with --to, similar to --cc and --bcc.

Get the status of the email delivery

We can keep checking the email delivery status until the status is OutForDelivery.

az communication email status get --message-id "\<messageId\>"
  • Replace "<messageId>" with the messageId from the response of the send request.
Status Name Description
NotStarted We're not sending this status from our service at this time.
Running The email send operation is currently in progress and being processed.
Succeeded The email send operation has completed without error and the email is out for delivery. Any detailed status about the email delivery beyond this stage can be obtained either through Azure Monitor or through Azure Event Grid. Learn how to subscribe to email events
Failed The email send operation wasn't successful and encountered an error. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.
Canceled The email send operation was canceled before it could complete. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.

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

Understanding the Email 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 mime type string, and binary data for content.
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. You have to specify atleast one of PlainText or Html content
EmailCustomHeader This class allows for the addition of a name and value pair for a custom header. Email importance can also be specified through these headers using the header name 'x-priority' or 'x-msmail-priority'
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.
EmailSendOperation This class represents the asynchronous email send operation and is returned from email send api call.
EmailSendResult This class holds the results of the email send operation. It has an operation ID, operation status and error object (when applicable).

EmailSendResult returns the following status on the email operation performed.

Status Description
NotStarted We're not sending this status from our service at this time.
Running The email send operation is currently in progress and being processed.
Succeeded The email send operation has completed without error and the email is out for delivery. Any detailed status about the email delivery beyond this stage can be obtained either through Azure Monitor or through Azure Event Grid. Learn how to subscribe to email events
Failed The email send operation wasn't successful and encountered an error. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.
Canceled The email send operation was canceled before it could complete. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.

Prerequisites

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

Note

We can also send an email from our own verified domain. Add custom verified domains to Email Communication Service.

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.

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

Creating the email client with authentication

Open Program.cs and replace the existing code with the following to add using directives for including the Azure.Communication.Email 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;

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

  }
}
}

Option 1: Authenticate using a connection string

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 following code 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);

Option 2: Authenticate using Azure Active Directory

To authenticate using Azure Active Directory, install the Azure.Identity library package for .NET by using the dotnet add package command.

dotnet add package Azure.Identity

Open Program.cs in a text editor and replace the body of the Main method with code to initialize an EmailClient using DefaultAzureCredential. The Azure Identity SDK reads values from three environment variables at runtime to authenticate the application. Learn how to create an Azure Active Directory Registered Application and set the environment variables.

// This code demonstrates how to authenticate to your Communication Service resource using
// DefaultAzureCredential and the environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID,
// and AZURE_CLIENT_SECRET.
string resourceEndpoint = "<ACS_RESOURCE_ENDPOINT>";
EmailClient emailClient = new EmailClient(new Uri(resourceEndpoint), new DefaultAzureCredential());

Option 3: Authenticate using AzureKeyCredential

Email clients can also be authenticated using an AzureKeyCredential. Both the key and the endpoint can be founded on the "Keys" pane under "Settings" in your Communication Services Resource.

var key = new AzureKeyCredential("<your-key-credential>");
var endpoint = new Uri("<your-endpoint-uri>");

var emailClient = new EmailClient(endpoint, key);

Basic Email Sending

Construct your email message

To send an email message, you need to:

  • Define the email subject and body.
  • Define your Sender Address. Construct your email message with your Sender information you get your MailFrom address from your verified domain.
  • Define the Recipient Address.
  • Call the SendAsync 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

var subject = "Welcome to Azure Communication Service Email APIs.";
var htmlContent = "<html><body><h1>Quick send email test</h1><br/><h4>This email message is sent from Azure Communication Service Email.</h4><p>This mail was send using .NET SDK!!</p></body></html>";
var sender = "donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net";
var recipient = "emailalias@contoso.com";

Send and get the email send status

To send an email message, you need to:

  • Call SendSync method that sends the email request as an asynchronous operation. Call with Azure.WaitUntil.Completed if your method should wait to return until the long-running operation has completed on the service. Call with Azure.WaitUntil.Started if your method should return after starting the operation.
  • SendAsync method returns EmailSendOperation that returns "Succeeded" EmailSendStatus if email is out for delivery. Add this code to the end of Main method in Program.cs:
try
{
  Console.WriteLine("Sending email...");
  EmailSendOperation emailSendOperation = await emailClient.SendAsync(Azure.WaitUntil.Completed, sender, recipient, subject, htmlContent);
  EmailSendResult statusMonitor = emailSendOperation.Value;

  string operationId = emailSendOperation.Id;
  var emailSendStatus = statusMonitor.Status;

  if (emailSendStatus == EmailSendStatus.Succeeded)
  {
      Console.WriteLine($"Email send operation succeeded with OperationId = {operationId}.\nEmail is out for delivery.");
  }
  else
  {
      var error = statusMonitor.Error;
      Console.WriteLine($"Failed to send email.\n OperationId = {operationId}.\n Status = {emailSendStatus}.");
      Console.WriteLine($"Error Code = {error.Code}, Message = {error.Message}");
      return;
  }
}
catch (Exception ex)
{
  Console.WriteLine($"Error in sending email, {ex}");
} 

Getting email delivery status

EmailSendOperation only returns email operation status. To get the actual email delivery status, you can subscribe to "EmailDeliveryReportReceived" event that is generated when the email delivery is completed. The event returns the following delivery state:

  • Delivered.
  • Failed.
  • Quarantined.

See Handle Email Events for details.

You can also now subscribe to Email Operational logs that provide information related to delivery metrics for messages sent from the Email service.

  • Email Send Mail operational logs - provides detailed information related to the Email service send mail requests.
  • Email Status Update operational logs - provides message and recipient level delivery status updates related to the Email service send mail requests.

See how to Get started with log analytics in Azure Communication Service

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

Advanced Sending

Sending email async and polling for the email send status

When you call SendAsync with Azure.WaitUntil.Started, your method returns back after starting the operation. The method returns EmailSendOperation object. You can call UpdateStatusAsync method to refresh the email operation status.

The returned EmailSendOperation object contains an EmailSendStatus object that contains:

  • Current status of the Email Send operation.
  • An error object with failure details if the current status is in a failed state.
try
{
  Console.WriteLine("Sending email with Async no Wait...");
  EmailSendOperation emailSendOperation = await emailClient.SendAsync(Azure.WaitUntil.Started,  sender, recipient, subject, htmlContent);

  var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(2));

  // Poll for email send status manually
  while (!cancellationToken.IsCancellationRequested)
  {
      await emailSendOperation.UpdateStatusAsync();
      if (emailSendOperation.HasCompleted)
      {
          break;
      }
      Console.WriteLine("Email send operation is still running...");
      await Task.Delay(1000);
  }

  if (emailSendOperation.HasValue)
  {
    EmailSendResult statusMonitor = emailSendOperation.Value;
    string operationId = emailSendOperation.Id;
    var emailSendStatus = statusMonitor.Status;

    if (emailSendStatus == EmailSendStatus.Succeeded)
    {
        Console.WriteLine($"Email send operation succeeded with OperationId = {operationId}.\nEmail is out for delivery.");
    }
    else
    {
        var error = statusMonitor.Error;
        Console.WriteLine($"Failed to send email.\n OperationId = {operationId}.\n Status = {emailSendStatus}.");
        Console.WriteLine($"Error Code = {error.Code}, Message = {error.Message}");
        return;
    }
  }
  else if (cancellationToken.IsCancellationRequested)
  {
    Console.WriteLine($"We have timed out while  polling for email status");
  }
}
catch (Exception ex)
{
  Console.WriteLine($"Error in sending email, {ex}");
}

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

dotnet run

Sample code

You can download the sample app from GitHub

Send an email message using the object model to construct the email payload

  • Construct the email content and body using EmailContent.
  • Add Recipients.
  • Set email importance through custom headers.
  • Construct your email message using your sender email address, defined in the MailFrom list of the domain linked in your Communication Services Resource.
  • Include your EmailContent and EmailRecipients, optionally adding attachments.

EmailContent emailContent = new EmailContent("Welcome to Azure Communication Service Email APIs.");

var subject = "Welcome to Azure Communication Service Email APIs.";

var emailContent = new EmailContent(subject)
{
  PlainText = "This email message is sent from Azure Communication Service Email using .NET SDK.",
  Html = "<html><body><h1>Quick send email test</h1><br/><h4>This email message is sent from Azure Communication Service Email using .NET SDK.</h4></body></html>"
};

var sender = "donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net";
 
List<EmailAddress> emailAddresses = new List<EmailAddress> { new EmailAddress("emailalias@contoso.com") { DisplayName = "Friendly Display Name" }};

EmailRecipients emailRecipients = new EmailRecipients(emailAddresses);

var emailMessage = new EmailMessage(sender, emailRecipients, emailContent)
{
  // Header name is "x-priority" or "x-msmail-priority"
  // Header value is a number from 1 to 5. 1 or 2 = High, 3 = Normal, 4 or 5 = Low
  // Not all email clients recognize this header directly (outlook client does recognize)
  Headers =
  {
      // Set Email Importance to High
      { "x-priority", "1" },
      { "", "" }
  }
};

try
{
  Console.WriteLine("Sending email to multiple recipients...");
  EmailSendOperation emailSendOperation = await emailClient.SendAsync(Azure.WaitUntil.Completed, emailMessage);
  EmailSendResult statusMonitor = emailSendOperation.Value;

  string operationId = emailSendOperation.Id;
  var emailSendStatus = statusMonitor.Status;

  if (emailSendStatus == EmailSendStatus.Succeeded)
  {
      Console.WriteLine($"Email send operation succeeded with OperationId = {operationId}.\nEmail is out for delivery.");
  }
  else
  {
      Console.WriteLine($"Failed to send email. \n OperationId = {operationId}. \n Status = {emailSendStatus}");
      return;
  }
}
catch (Exception ex)
{
  Console.WriteLine($"Error in sending email, {ex}");
}

Send an email message to multiple recipients

We can define multiple recipients by adding more EmailAddresses to the EmailRecipients object. These addresses can be added as To, CC, or BCC recipients.

var toRecipients = new List<EmailAddress>
{
  new EmailAddress("<emailalias1@emaildomain.com>"),
  new EmailAddress("<emailalias2@emaildomain.com>"),
};

var ccRecipients = new List<EmailAddress>
{
  new EmailAddress("<ccemailalias@emaildomain.com>"),
};

var bccRecipients = new List<EmailAddress>
{
  new EmailAddress("<bccemailalias@emaildomain.com>"),
};

EmailRecipients emailRecipients = new EmailRecipients(toRecipients, ccRecipients, bccRecipients);

You can download the sample app demonstrating this action from GitHub

Send an email message with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attachment file and encode it using Base64.


var filePath = "C:\Users\Documents\attachment.pdf";
byte[] bytes = File.ReadAllBytes(filePath);
var contentBinaryData = new BinaryData(bytes);
var emailAttachment = new EmailAttachment("attachment.pdf", MediaTypeNames.Application.Pdf, contentBinaryData);
emailMessage.Attachments.Add(emailAttachment);

You can download the sample app demonstrating this action from GitHub

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

Understanding the email 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 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 mime type string, and binary data for content.
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. You have to specify at least one of PlainText or Html content.
EmailCustomHeader This class allows for the addition of a name and value pair for a custom header. Email importance can also be specified through these headers using the header name 'x-priority' or 'x-msmail-priority'.
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.
EmailSendResult This class holds the results of the email send operation. It has an operation ID, operation status and error object (when applicable).
EmailSendStatus This class represents the set of statuses of an email send operation.

EmailSendResult returns the following status on the email operation performed.

Status Name Description
isStarted Returns true if the email send operation is currently in progress and being processed.
isCompleted Returns true if the email send operation has completed without error and the email is out for delivery. Any detailed status about the email delivery beyond this stage can be obtained either through Azure Monitor or through Azure Event Grid. Learn how to subscribe to email events
result Property that exists if the email send operation has concluded.
error Property that exists if the email send operation wasn't successful and encountered an error. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.
isCanceled True if the email send operation was canceled before it could complete. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.

Prerequisites

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

Note

We can also send an email from our own verified domain. Add custom verified domains to Email Communication Service.

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.

Set up the application environment

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". The following section demonstrates how to add the source code for this quickstart to the newly created file.

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.

Creating the email client with authentication

Option 1: Authenticate using a connection string

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

The following code 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'];
const emailClient = new EmailClient(connectionString);

Option 2: Authenticate using Azure Active Directory

You can also authenticate with Azure Active Directory using the Azure Identity library. To use the DefaultAzureCredential provider in the following snippet, or other credential providers provided with the Azure SDK, install the @azure/identity package:

npm install @azure/identity

The @azure/identity package provides various credential types that your application can use to authenticate. The README for @azure/identity provides more details and samples to get you started. AZURE_CLIENT_SECRET, AZURE_CLIENT_ID and AZURE_TENANT_ID environment variables are needed to create a DefaultAzureCredential object.

import { DefaultAzureCredential } from "@azure/identity";
import { EmailClient } from "@azure/communication-email";

const endpoint = "https://<resource-name>.communication.azure.com";
let credential = new DefaultAzureCredential();

const emailClient = new EmailClient(endpoint, credential);

Option 3: Authenticate using AzureKeyCredential

Email clients can also be authenticated using an AzureKeyCredential. Both the key and the endpoint can be founded on the "Keys" pane under "Settings" in your Communication Services Resource.

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

var key = new AzureKeyCredential("<your-key-credential>");
var endpoint = "<your-endpoint-uri>";

const emailClient = new EmailClient(endpoint, key);

For simplicity, this quickstart uses connection strings, but in production environments, we recommend using service principals.

Basic email sending

Send an email message

To send an email message, call the beginSend function from the EmailClient. This method returns a poller that checks on the status of the operation and retrieves the result once it's finished.


async function main() {
  try {
    const message = {
      senderAddress: "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>",
      content: {
        subject: "Welcome to Azure Communication Services Email",
        plainText: "This email message is sent from Azure Communication Services Email using the JavaScript SDK.",
      },
      recipients: {
        to: [
          {
            address: "<emailalias@emaildomain.com>",
            displayName: "Customer Name",
          },
        ],
      },
    };

    const poller = await emailClient.beginSend(message);
    const response = await poller.pollUntilDone();
  } catch (e) {
    console.log(e);
  }
}

main();

Make these replacements in the code:

  • Replace <emailalias@emaildomain.com> with the email address you would like to send a message to.
  • Replace <donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net> with the MailFrom address of your verified domain.

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

Advanced sending

Send an email message to multiple recipients

To send an email message to multiple recipients, add an object for each recipient type and an object for each recipient. These addresses can be added as To, CC, or BCC recipients.

const message = {
  senderAddress: "<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: [
      {
        address: "customer1@domain.com",
        displayName: "Customer Name 1",
      },
      {
        address: "customer2@domain.com",
        displayName: "Customer Name 2",
      }
    ],
    cc: [
      {
        address: "ccCustomer1@domain.com",
        displayName: " CC Customer 1",
      },
      {
        address: "ccCustomer2@domain.com",
        displayName: "CC Customer 2",
      }
    ],
    bcc: [
      {
        address: "bccCustomer1@domain.com",
        displayName: " BCC Customer 1",
      },
      {
        address: "bccCustomer2@domain.com",
        displayName: "BCC Customer 2",
      }
    ]
  }
};

You can download the sample app demonstrating this action from GitHub

Send an email message with attachments

We can add an attachment by defining an attachment object and adding it to our message. Read the attachment file and encode it using Base64.

const filePath = "<path-to-your-file>";

const message = {
  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 JavaScript SDK.>"
  },
  recipients: {
    to: [
      {
        address: "<emailalias@emaildomain.com>",
        displayName: "Customer Name",
      }
    ]
  },
  attachments: [
    {
      name: path.basename(filePath),
      contentType: "text/plain",
      contentInBase64: readFileSync(filePath, "base64"),
    }
  ]
};

const response = await emailClient.send(message);

You can download the sample app demonstrating this action from GitHub

Get started with Azure Communication Services by using the Communication Services Java Email SDK to send Email messages.

Understanding the email object model

The following classes and interfaces handle some of the major features of the Azure Communication Services Email SDK for Python.

Name Description
EmailAddress This class 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.
EmailMessage This class combines the sender, content, and recipients. Custom headers, attachments, and reply-to email addresses can optionally be added, as well.
EmailSendResult This class holds the results of the email send operation. It has an operation ID, operation status and error object (when applicable).
EmailSendStatus This class represents the set of statuses of an email send operation.

EmailSendResult returns the following status on the email operation performed.

Status Name Description
NOT_STARTED We're not sending this status from our service at this time.
IN_PROGRESS The email send operation is currently in progress and being processed.
SUCCESSFULLY_COMPLETED The email send operation has completed without error and the email is out for delivery. Any detailed status about the email delivery beyond this stage can be obtained either through Azure Monitor or through Azure Event Grid. Learn how to subscribe to email events
FAILED The email send operation wasn't successful and encountered an error. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.
USER_CANCELLED The email send operation was canceled before it could complete. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.

Prerequisites

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

Note

We can also send an email from our own verified domain Add custom verified domains to Email Communication Service.

Prerequisite check

  • In a terminal or command window, run mvn -v to check that Maven 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.

Set up the application environment

To set up an environment for sending emails, take the steps in the following sections.

Create a new Java application

Open your terminal or command window and navigate to the directory where you would like to create your Java application. Run the following command to generate the Java project from the maven-archetype-quickstart template.

mvn archetype:generate -DarchetypeArtifactId="maven-archetype-quickstart" -DarchetypeGroupId="org.apache.maven.archetypes" -DarchetypeVersion="1.4" -DgroupId="com.communication.quickstart" -DartifactId="communication-quickstart"

The generate goal creates a directory with the same name as the artifactId value. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model (POM).

Install the package

Open the pom.xml file in your text editor. Add the following dependency element to the group of dependencies.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-email</artifactId>
    <version>1.0.0-beta.2</version>
</dependency>

Set up the app framework

Open /src/main/java/com/communication/quickstart/App.java in a text editor, add import directives, and remove the System.out.println("Hello world!"); statement:

package com.communication.quickstart;

import com.azure.communication.email.models.*;
import com.azure.communication.email.*;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.SyncPoller;

public class App
{
    public static void main( String[] args )
    {
        // Quickstart code goes here.
    }
}

Creating the email client with authentication

Option 1: Authenticate using a connection string

To authenticate a client, you instantiate an EmailClient with your connection string. Learn how to manage your resource's connection string. You can also initialize the client with any custom HTTP client that implements the com.azure.core.http.HttpClient interface.

To instantiate a client, add the following code to the main method:

// You can get your connection string from your resource in the Azure portal.
String connectionString = "endpoint=https://<resource-name>.communication.azure.com/;accesskey=<access-key>";

EmailClient emailClient = new EmailClientBuilder()
    .connectionString(connectionString)
    .buildClient();

Option 2: Authenticate using Azure Active Directory

A DefaultAzureCredential object must be passed to the EmailClientBuilder via the credential() method. An endpoint must also be set via the endpoint() method.

The AZURE_CLIENT_SECRET, AZURE_CLIENT_ID, and AZURE_TENANT_ID environment variables are needed to create a DefaultAzureCredential object.

// You can find your endpoint and access key from your resource in the Azure portal
String endpoint = "https://<resource-name>.communication.azure.com/";
EmailClient emailClient = new EmailClientBuilder()
    .endpoint(endpoint)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Option 3: Authenticate using AzureKeyCredential

Email clients can also be created and authenticated using the endpoint and Azure Key Credential acquired from an Azure Communication Resource in the Azure portal.

String endpoint = "https://<resource-name>.communication.azure.com";
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
EmailClient emailClient = new EmailClientBuilder()
    .endpoint(endpoint)
    .credential(azureKeyCredential)
    .buildClient();

For simplicity, this quickstart uses connection strings, but in production environments, we recommend using service principals.

Basic email sending

To send an email message, call the beginSend function from the EmailClient. This method returns a poller, which can be used to check on the status of the operation and retrieve the result once it's finished.

EmailMessage message = new EmailMessage()
    .setSenderAddress("<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>")
    .setToRecipients("<emailalias@emaildomain.com>")
    .setSubject("Welcome to Azure Communication Services Email")
    .setBodyPlainText("This email message is sent from Azure Communication Services Email using the Java SDK.");

SyncPoller<EmailSendResult, EmailSendResult> poller = emailClient.beginSend(message, null);
PollResponse<EmailSendResult> response = poller.waitForCompletion();

System.out.println("Operation Id: " + response.getValue().getId());

Make these replacements in the code:

  • Replace <emailalias@emaildomain.com> with the email address you would like to send a message to.
  • Replace <donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net> with the MailFrom address of your verified domain.

Run the code

  1. Navigate to the directory that contains the pom.xml file and compile the project by using the mvn command.

    mvn compile
    
  2. Build the package.

    mvn package
    
  3. Run the following mvn command to execute the app.

    mvn exec:java -D"exec.mainClass"="com.communication.quickstart.App" -D"exec.cleanupDaemonThreads"="false"
    

Sample code

You can download the sample app from GitHub

Advanced sending

Send an email message to multiple recipients

To send an email message to multiple recipients, add the new addresses in the appropriate EmailMessage setter. These addresses can be added as To, CC, or BCC recipients.

EmailMessage message = new EmailMessage()
    .setSenderAddress("<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>")
    .setSubject("Welcome to Azure Communication Services Email")
    .setBodyPlainText("This email message is sent from Azure Communication Services Email using the Java SDK.")
    .setToRecipients("<recipient1@emaildomain.com>", "<recipient2@emaildomain.com>")
    .setCcRecipients("<recipient3@emaildomain.com>")
    .setBccRecipients("<recipient4@emaildomain.com>");

SyncPoller<EmailSendResult, EmailSendResult> poller = emailClient.beginSend(message, null);
PollResponse<EmailSendResult> response = poller.waitForCompletion();

System.out.println("Operation Id: " + response.getValue().getId());

To customize the email message recipients further, you can instantiate the EmailAddress objects and pass that them to the appropriate EmailMessage setters.

EmailAddress toAddress1 = new EmailAddress("<recipient1@emaildomain.com>")
    .setDisplayName("Recipient");

EmailAddress toAddress2 = new EmailAddress("<recipient2@emaildomain.com>")
    .setDisplayName("Recipient 2");

EmailMessage message = new EmailMessage()
    .setSenderAddress("<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>")
    .setSubject("Welcome to Azure Communication Services Email")
    .setBodyPlainText("This email message is sent from Azure Communication Services Email using the Java SDK.")
    .setToRecipients(toAddress1, toAddress2);

SyncPoller<EmailSendResult, EmailSendResult> poller = emailClient.beginSend(message, null);
PollResponse<EmailSendResult> response = poller.waitForCompletion();

System.out.println("Operation Id: " + response.getValue().getId());

You can download the sample app demonstrating this action from GitHub

Send an email message with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attachment file and encode it using Base64.

BinaryData attachmentContent = BinaryData.fromFile(new File("C:/attachment.txt").toPath());
EmailAttachment attachment = new EmailAttachment(
    "attachment.txt",
    "text/plain",
    attachmentContent
);

EmailMessage message = new EmailMessage()
    .setSenderAddress("<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>")
    .setToRecipients("<emailalias@emaildomain.com>")
    .setSubject("Welcome to Azure Communication Services Email")
    .setBodyPlainText("This email message is sent from Azure Communication Services Email using the Java SDK.");
    .setAttachments(attachment);

SyncPoller<EmailSendResult, EmailSendResult> poller = emailClient.beginSend(message, null);
PollResponse<EmailSendResult> response = poller.waitForCompletion();

System.out.println("Operation Id: " + response.getValue().getId());

You can download the sample app demonstrating this action from GitHub

Get started with Azure Communication Services by using the Communication Services Python Email SDK to send Email messages.

Understanding the email object model

The following JSON message template & response object demonstrate some of the major features of the Azure Communication Services Email SDK for Python.

message = {
    "content": {
        "subject": "str",  # Subject of the email message. Required.
        "html": "str",  # Optional. Html version of the email message.
        "plainText": "str"  # Optional. Plain text version of the email
            message.
    },
    "recipients": {
        "to": [
            {
                "address": "str",  # Email address. Required.
                "displayName": "str"  # Optional. Email display name.
            }
        ],
        "bcc": [
            {
                "address": "str",  # Email address. Required.
                "displayName": "str"  # Optional. Email display name.
            }
        ],
        "cc": [
            {
                "address": "str",  # Email address. Required.
                "displayName": "str"  # Optional. Email display name.
            }
        ]
    },
    "senderAddress": "str",  # Sender email address from a verified domain. Required.
    "attachments": [
        {
            "contentInBase64": "str",  # Base64 encoded contents of the attachment. Required.
            "contentType": "str",  # MIME type of the content being attached. Required.
            "name": "str"  # Name of the attachment. Required.
        }
    ],
    "userEngagementTrackingDisabled": bool,  # Optional. Indicates whether user engagement tracking should be disabled for this request if the resource-level user engagement tracking setting was already enabled in the control plane.
    "headers": {
        "str": "str"  # Optional. Custom email headers to be passed.
    },
    "replyTo": [
        {
            "address": "str",  # Email address. Required.
            "displayName": "str"  # Optional. Email display name.
        }
    ]
}

response = {
    "id": "str",  # The unique id of the operation. Uses a UUID. Required.
    "status": "str",  # Status of operation. Required. Known values are:
        "NotStarted", "Running", "Succeeded", "Failed", and "Canceled".
    "error": {
        "additionalInfo": [
            {
                "info": {},  # Optional. The additional info.
                "type": "str"  # Optional. The additional info type.
            }
        ],
        "code": "str",  # Optional. The error code.
        "details": [
            ...
        ],
        "message": "str",  # Optional. The error message.
        "target": "str"  # Optional. The error target.
    }
}

The response.status values are explained further in the following table.

Status Name Description
InProgress The email send operation is currently in progress and being processed.
Succeeded The email send operation has completed without error and the email is out for delivery. Any detailed status about the email delivery beyond this stage can be obtained either through Azure Monitor or through Azure Event Grid. Learn how to subscribe to email events
Failed The email send operation wasn't successful and encountered an error. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.
Canceled The email send operation was canceled before it could complete. The email wasn't sent. The result contains an error object with more details on the reason for failure or cancellation.

Prerequisites

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

Note

We can also send an email from our own verified domain. Add custom verified domains to Email Communication Service.

Prerequisite check

  • In a terminal or command window, run the python --version command to check that Python 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.

Set up the application environment

To set up an environment for sending emails, take the steps in the following sections.

Create a new Python application

  1. Open your terminal or command window. Then use the following command to create a virtual environment and activate it. This command creates a new directory for your app.

    python -m venv email-quickstart
    
  2. Navigate to the root directory of the virtual environment and activate it using the following commands.

    cd email-quickstart
    .\Scripts\activate
    
  3. Use a text editor to create a file called send-email.py in the project root directory and add the structure for the program, including basic exception handling.

    import os
    from azure.communication.email import EmailClient
    
    try:
        # Quickstart code goes here.
    except Exception as ex:
        print('Exception:')
        print(ex)
    

In the following sections, you add all the source code for this quickstart to the send-email.py file that you created.

Install the package

While still in the application directory, install the Azure Communication Services Email SDK for Python package by using the following command.

pip install azure-communication-email

Creating the email client with authentication

Option 1: Authenticate using a connection string

Instantiate an EmailClient with your connection string. Learn how to manage your resource's connection string.

# Create the EmailClient object that you use to send Email messages.
email_client = EmailClient.from_connection_string(<connection_string>)

Option 2: Authenticate using Azure Active Directory

You can also use Active Directory authentication using DefaultAzureCredential.

from azure.communication.email import EmailClient
from azure.identity import DefaultAzureCredential

# To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
endpoint = "https://<resource-name>.communication.azure.com"
email_client = EmailClient(endpoint, DefaultAzureCredential())

Option 3: Authenticate using AzureKeyCredential

Email clients can also be authenticated using an AzureKeyCredential. Both the key and the endpoint can be founded on the "Keys" pane under "Settings" in your Communication Services Resource.

from azure.communication.email import EmailClient
from azure.core.credentials import AzureKeyCredential

key = AzureKeyCredential("<your-key-credential>");
endpoint = "<your-endpoint-uri>";

email_client = EmailClient(endpoint, key);

For simplicity, this quickstart uses connection strings, but in production environments, we recommend using service principals.

Basic email sending

Send an email message

To send an email message, you need to:

  • Construct the message with the following values:
    • senderAddress: A valid sender email address, found in the MailFrom field in the overview pane of the domain linked to your Email Communication Services Resource.
    • recipients: An object with a list of email recipients, and optionally, lists of CC & BCC email recipients.
    • content: An object containing the subject, and optionally the plaintext or HTML content, of an email message.
  • Call the begin_send method, which returns the result of the operation.
message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {
                "address": "<emailalias@emaildomain.com>",
                "displayName": "Customer Name"
            }
        ]
    },
    "senderAddress": "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>"
}

poller = email_client.begin_send(message)
print("Result: " + poller.result())

Make these replacements in the code:

  • Replace <emailalias@emaildomain.com> with the email address you would like to send a message to.
  • Replace <donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net> with the MailFrom address of your verified domain.

Get the status of the email delivery

We can poll for the status of the email delivery by setting a loop on the operation status object returned from the EmailClient's begin_send method:

POLLER_WAIT_TIME = 10

try:
    email_client = EmailClient.from_connection_string(connection_string)

    poller = client.begin_send(message);

    time_elapsed = 0
    while not poller.done():
        print("Email send poller status: " + poller.status())

        poller.wait(POLLER_WAIT_TIME)
        time_elapsed += POLLER_WAIT_TIME

        if time_elapsed > 18 * POLLER_WAIT_TIME:
            raise RuntimeError("Polling timed out.")

    if poller.status() == "Succeeded":
        print(f"Successfully sent the email (operation id: {poller.result()['id']})")
    else:
        raise RuntimeError(str(poller.result()["error"]))

except Exception as ex:
    print(ex)

Run the code

Run the application from your application directory with the python command.

python send-email.py

Sample code

You can download the sample app from GitHub

Advanced sending

Send an email message to multiple recipients

We can define multiple recipients by adding more EmailAddresses to the EmailRecipients object. These addresses can be added as to, cc, or bcc recipient lists accordingly.

message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {"address": "<recipient1@emaildomain.com>", "displayName": "Customer Name"},
            {"address": "<recipient2@emaildomain.com>", "displayName": "Customer Name 2"}
        ],
        "cc": [
            {"address": "<recipient1@emaildomain.com>", "displayName": "Customer Name"},
            {"address": "<recipient2@emaildomain.com>", "displayName": "Customer Name 2"}
        ],
        "bcc": [
            {"address": "<recipient1@emaildomain.com>", "displayName": "Customer Name"},
            {"address": "<recipient2@emaildomain.com>", "displayName": "Customer Name 2"}
        ]
    },
    "senderAddress": "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>"
}

You can download the sample app demonstrating this action from GitHub

Send an email message with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attachment file and encode it using Base64. Decode the bytes as a string and pass it into the EmailAttachment object.

import base64

with open("<your-attachment-path>", "rb") as file:
    file_bytes = file.read()

file_bytes_b64 = base64.b64encode(file_bytes)

message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {
                "address": "<recipient1@emaildomain.com>",
                "displayName": "Customer Name"
            }
        ]
    },
    "senderAddress": "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>",
    "attachments": [
        {
            "name": "<your-attachment-name>",
            "contentType": "<your-attachment-mime-type>",
            "contentInBase64": file_bytes_b64.decode()
        }
    ]
}

You can download the sample app demonstrating this action 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: