Quickstart: Use the email object model to send the email payload

In this quick start, you'll learn about how to use the email object model to send the email payload 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, 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.
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 using the object model to construct the email payload

  • Construct the email subject 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.
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>"
};
 
List<EmailAddress> emailAddresses = new List<EmailAddress> 
{ 
    new EmailAddress("emailalias@contoso.com", "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 = 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}");
}

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 manually poll for status when sending email using Azure Communication Services.

You may also want to: