Quickstart: Send email with attachments

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

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

Tip

Jump-start your email sending experience with Azure Communication Services by skipping straight to the Basic Email Sending and Advanced Email Sending sample code on GitHub.

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, binary data for content, and an optional content ID to define it as an inline attachment.
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.
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.

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

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

    }
  }
}

There are a few different options available for authenticating an email 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 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);

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.


// Create the email content
var emailContent = new EmailContent("Welcome to Azure Communication Service Email APIs.")
{
    PlainText = "This email message is sent from Azure Communication Service Email.",
    Html = "<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 sent using .NET SDK!!</p></body></html>"
};

// Create the EmailMessage
var emailMessage = new EmailMessage(
    senderAddress: "donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net" // The email address of the domain registered with the Communication Services resource
    recipientAddress: "emailalias@contoso.com"
    content: emailContent);

// Create the EmailAttachment
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);

try
{
    EmailSendOperation emailSendOperation = emailClient.Send(WaitUntil.Completed, emailMessage);
    Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

    /// Get the OperationId so that it can be used for tracking the message for troubleshooting
    string operationId = emailSendOperation.Id;
    Console.WriteLine($"Email operation id = {operationId}");
}
catch (RequestFailedException ex)
{
    /// OperationID is contained in the exception message and can be used for troubleshooting purposes
    Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
}

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

dotnet run

Allowed MIME types

For more information on acceptable MIME types for email attachments, see the allowed MIME types documentation.

Sample code

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.

Tip

Jump-start your email sending experience with Azure Communication Services by skipping straight to the Basic Email Sending and Advanced Email Sending sample code on GitHub.

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, binary data for content, and an optional content ID to define it as an inline attachment.
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.

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

There are a few different options available for authenticating an email client:

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

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

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: "<mime-type-for-your-file>",
      contentInBase64: readFileSync(filePath, "base64"),
    }
  ]
};

const poller = await emailClient.beginSend(message);
const response = await poller.pollUntilDone();

Allowed MIME types

For more information on acceptable MIME types for email attachments, see the allowed MIME types documentation.

Sample code

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.

Tip

Jump-start your email sending experience with Azure Communication Services by skipping straight to the Basic Email Sending and Advanced Email Sending sample code on GitHub.

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 MIME type string, a string of content bytes, and an optional content ID to define it as an inline attachment.
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.

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

There are a few different options available for authenticating an email 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 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());

Allowed MIME types

For more information on acceptable MIME types for email attachments, see the allowed MIME types documentation.

Sample code

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.

Tip

Jump-start your email sending experience with Azure Communication Services by skipping straight to the Basic Email Sending and Advanced Email Sending sample code on GitHub.

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": [
        {
            "name": "str"  # Name of the attachment. Required.
            "contentType": "str",  # MIME type of the content being attached. Required.
            "contentInBase64": "str",  # Base64 encoded contents of the attachment. Required.
            "contentId": "str" # Unique identifier (CID) to reference an inline attachment. Optional
        }
    ],
    "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", and "Failed".
    "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.

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

There are a few different options available for authenticating an email 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 with attachments

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

import base64

with open("<path-to-your-attachment>", "rb") as file:
    file_bytes_b64 = base64.b64encode(file.read())

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()
        }
    ]
}

poller = email_client.begin_send(message)
result = poller.result()

Allowed MIME types

For more information on acceptable MIME types for email attachments, see the allowed MIME types documentation.

Sample code

You can download the sample app demonstrating this action from GitHub

Troubleshooting

Email Delivery

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

Important

The success result returned by polling for the status of the send operation only validates the fact that the email has successfully been sent out for delivery. To get additional information about the status of the delivery on the recipient end, you will need to reference how to handle email events.

Email Throttling

If you see that your application is hanging it could be due to email sending being throttled. You can handle this through logging or by implementing a custom policy.

Note

This sandbox setup is to help developers start building the application. You can gradually request to increase the sending volume once the application is ready to go live. Submit a support request to raise your desired sending limit if you require sending a volume of messages exceeding the rate limits.

Clean up Azure Communication Service 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 an email with attachments using Azure Communication Services.

You may also want to: