Επεξεργασία

Κοινή χρήση μέσω


Quickstart: Manually poll for email status when sending email

In this quick start, you'll learn about how to manually poll for email status while sending email 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);

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.

//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 sent using .NET SDK!!</p></body></html>";
var sender = "donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net";
var recipient = "emailalias@contoso.com";

/// Send the email message with WaitUntil.Started
EmailSendOperation emailSendOperation = await emailClient.SendAsync(
    Azure.WaitUntil.Started,
    sender,
    recipient,
    subject,
    htmlContent);

/// Call UpdateStatus on the email send operation to poll for the status
/// manually.
try
{
    while (true)
    {
        await emailSendOperation.UpdateStatusAsync();
        if (emailSendOperation.HasCompleted)
        {
            break;
        }
        await Task.Delay(100);
    }

    if (emailSendOperation.HasValue)
    {
        Console.WriteLine($"Email queued for delivery. Status = {emailSendOperation.Value.Status}");
    }
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Email send failed with Code = {ex.ErrorCode} and Message = {ex.Message}");
}

/// 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}");

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

dotnet run

Sample code

You can download the sample app 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 manually poll for status when sending email using Azure Communication Services.

You may also want to: