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

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

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

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
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

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

Send an email message to multiple recipients

We can define multiple recipients by adding additional 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>"),
};

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

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

byte[] bytes = File.ReadAllBytes(filePath);
string attachmentFileInBytes = Convert.ToBase64String(bytes);

var emailAttachment = new EmailAttachment(
    "<your-attachment-name>",
    "<your-attachment-name>",
    attachmentFileInBytes
);

emailMessage.Add(emailAttachment);

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

Advanced

Send an email message to multiple recipients

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

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>" },
      { email: "<emailalias2@emaildomain.com>" }
    ],
    cc: [
      { 
        email: "<ccemailalias@emaildomain.com>" 
      }
    ],
    bcc: [
      { 
        email: "<bccemailalias@emaildomain.com>" }
      }
    ],
  },
};

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

const fs = require("fs");

const attachmentContent = fs.readFileSync(<your-attachment-path>).toString("base64");

const attachment = {
  name: "<your-attachment-name>",
  attachmentType: "<your-attachment-type>",
  contentBytesBase64: attachmentContent,
}

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>",
      },
    ],
  },
  attachments: [attachment]
};

You can download the sample app demonstrating this from GitHub

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

Completing this quickstart 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 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 -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

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.1</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 java.util.ArrayList;

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

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 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

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

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

Send an email message

To send an email message, you need to

  • Construct the EmailContent
  • Create an EmailAddress for the recipient
  • Construct the EmailRecipients
  • Construct the EmailMessage with the EmailContent, EmailAddress, and the sender information from the MailFrom address of your verified domain
  • Call the send method
EmailContent content = new EmailContent("Welcome to Azure Communication Services Email")
    .setPlainText("This email message is sent from Azure Communication Services Email using the Python SDK.");

EmailAddress emailAddress = new EmailAddress("<emailalias@emaildomain.com>");
ArrayList<EmailAddress> addressList = new ArrayList<>();
addressList.add(emailAddress);

EmailRecipients emailRecipients = new EmailRecipients(addressList);

EmailMessage emailMessage = new EmailMessage(
    "<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>",
    content,
    emailRecipients
);

SendEmailResult response = emailClient.send(emailMessage);

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.

Retrieve the Message ID of the email delivery

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

String message_id = response.getMessageId();

Get the status of the email delivery

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

long waitTime = 120*1000;
boolean timeout = true;
while (waitTime > 0)
{
    SendStatusResult sendStatus = emailClient.getSendStatus(messageId);
    System.out.printf("Send mail status for MessageId : <{%s}>, Status: [{%s}]", messageId, sendStatus.getStatus());

    if (!sendStatus.getStatus().toString().toLowerCase().equals(SendStatus.QUEUED.toString()))
    {
        timeout = false;
        break;
    }
    Thread.sleep(10000);
    waitTime = waitTime-10000;
}

if(timeout)
{
    System.out.println("Looks like we timed out for email");
}
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

  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 -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false
    

Sample code

You can download the sample app from GitHub

Advanced

Send an email message to multiple recipients

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

EmailAddress toEmailAddress1 = new EmailAddress("<emailalias1@emaildomain.com>");
EmailAddress toEmailAddress2 = new EmailAddress("<emailalias2@emaildomain.com>");

EmailAddress ccEmailAddress = new EmailAddress("<ccemailalias@emaildomain.com>");
EmailAddress bccEmailAddress = new EmailAddress("<bccemailalias@emaildomain.com>");

ArrayList<EmailAddress> toAddressList = new ArrayList<>();
toAddressList.add(toEmailAddress1);
toAddressList.add(toEmailAddress2);

ArrayList<EmailAddress> ccAddressList = new ArrayList<>();
ccAddressList.add(ccEmailAddress);

ArrayList<EmailAddress> bccAddressList = new ArrayList<>();
bccAddressList.add(bccEmailAddress);

EmailRecipients emailRecipients = new EmailRecipients(toAddressList)
    .setCc(ccAddressList)
    .setBcc(bccAddressList);

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

File file = new File("<your-attachment-path>");

byte[] fileContent = null;
try {
    fileContent = Files.readAllBytes(file.toPath());
} catch (Exception e) {
    System.out.println(e);
}

String b64file = Base64.getEncoder().encodeToString(fileContent);

EmailAttachment attachment = new EmailAttachment("<your-attachment-name>", "<your-attachment-file-type>", b64file);

ArrayList<EmailAttachment> attachmentList = new ArrayList<>();
attachmentList.add(attachment);

EmailMessage emailMessage = new EmailMessage("<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>", content)
    .setRecipients(emailRecipients)
    .setAttachments(attachmentList);

You can download the sample app demonstrating this from GitHub

Get started with Azure Communication Services by using the Communication Services Python Email SDK 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 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 new directory for your app and navigate to it.

    mkdir email-quickstart && cd email-quickstart
    
  2. 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'll add all the source code for this quickstart to the send-email.py file that you just 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

Object model

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

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

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>)

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

Send an email message

To send an email message, you need to

  • Construct the EmailContent
  • Create an EmailAddress for the recipient
  • Construct the EmailRecipients
  • Construct the EmailMessage with the EmailContent, EmailAddress, and the sender information from the MailFrom address of your verified domain
  • Call the send method
content = EmailContent(
    subject="Welcome to Azure Communication Services Email",
    plain_text="This email message is sent from Azure Communication Services Email using the Python SDK.",
)

address = EmailAddress(email="<emailalias@emaildomain.com>")
recipient = EmailRecipients(to=[address])

message = EmailMessage(
            sender="<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>",
            content=content,
            recipients=recipients
        )

response = email_client.send(message)

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.

Retrieve the Message ID of the email delivery

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

message_id = response.message_id

Get the status of the email delivery

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

counter = 0
while True:
    counter+=1
    send_status = client.get_send_status(message_id)

    if (send_status):
        print(f"Email status for message_id {message_id} is {send_status.status}.")
    if (send_status.status.lower() == "queued" and counter < 12):
        time.sleep(10)  # wait for 10 seconds before checking next time.
        counter +=1
    else:
        if(send_status.status.lower() == "outfordelivery"):
            print(f"Email delivered for message_id {message_id}.")
            break
        else:
            print("Looks like we timed out for checking email send status.")
            break
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

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

Send an email message to multiple recipients

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

to_address_1 = EmailAddress(email="<emailalias1@emaildomain.com>")
to_address_2 = EmailAddress(email="<emailalias2@emaildomain.com>")
cc_address = EmailAddress(email="<ccemailalias@emaildomain.com>")
bcc_address = EmailAddress(email="<bccemailalias@emaildomain.com>")

recipient = EmailRecipients(to=[to_address_1, to_address_2], cc=[cc_address], bcc=[bcc_address])

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

attachment = EmailAttachment(
    name="<your-attachment-name>",
    attachment_type="<your-attachment-file-type>",
    content_bytes_base64=file_bytes_b64.decode()
)

message = EmailMessage(
    sender="<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>",
    content=content,
    recipients=recipients,
    attachments=[attachment]
)

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