Skip to content

Commit 3a7e341

Browse files
authored
Merge pull request #280338 from v-vprasannak/EmailServiceSendEmail
Email Service - Send email - Update quick start to recommend customers to use manual pooling
2 parents a7ad9bc + c9bd9d9 commit 3a7e341

File tree

3 files changed

+334
-1
lines changed

3 files changed

+334
-1
lines changed
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
---
2+
title: include file
3+
description: Send email.net sdk include file
4+
author: v-vprasannak
5+
manager: koagbakp
6+
services: azure-communication-services
7+
ms.author: v-vprasannak
8+
ms.date: 07/09/2024
9+
ms.topic: include
10+
ms.service: azure-communication-services
11+
---
12+
13+
Get started with Azure Communication Services by using the Communication Services C# Email client library to send Email messages.
14+
15+
> [!TIP]
16+
> Jump-start your email sending experience with Azure Communication Services by skipping straight to the [Basic Email Sending](https://github.com/Azure-Samples/communication-services-dotnet-quickstarts/tree/main/SendEmail) and [Advanced Email Sending](https://github.com/Azure-Samples/communication-services-dotnet-quickstarts/tree/main/SendEmailAdvanced) sample code on GitHub.
17+
18+
## Understanding the Email Object model
19+
20+
The following classes and interfaces handle some of the major features of the Azure Communication Services Email Client library for C#.
21+
22+
23+
| Name | Description |
24+
| --------------------| -----------------------------------------------------------------------------------------------------------------------------------------------------|
25+
| EmailAddress | This class contains an email address and an option for a display name. |
26+
| EmailAttachment | This class creates an email attachment by accepting a unique ID, email attachment [MIME type](../../../concepts/email/email-attachment-allowed-mime-types.md) string, and binary data for content. |
27+
| EmailClient | This class is needed for all email functionality. You instantiate it with your connection string and use it to send email messages. |
28+
| EmailClientOptions | This class can be added to the EmailClient instantiation to target a specific API version. |
29+
| 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 |
30+
| 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' |
31+
| EmailMessage | This class combines the sender, content, and recipients. Custom headers, attachments, and reply-to email addresses can optionally be added, as well. |
32+
| EmailRecipients | This class holds lists of EmailAddress objects for recipients of the email message, including optional lists for CC & BCC recipients. |
33+
| EmailSendOperation | This class represents the asynchronous email send operation and is returned from email send api call. |
34+
| EmailSendResult | This class holds the results of the email send operation. It has an operation ID, operation status and error object (when applicable). |
35+
36+
37+
EmailSendResult returns the following status on the email operation performed.
38+
39+
40+
| Status | Description |
41+
| ---------------------| --------------------------------------------------------------------------------------------------------------------------------------------|
42+
| NotStarted | We're not sending this status from our service at this time. |
43+
| Running | The email send operation is currently in progress and being processed. |
44+
| 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](../handle-email-events.md) |
45+
| 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. |
46+
47+
## Prerequisites
48+
49+
- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
50+
- The latest version [.NET Core client library](https://dotnet.microsoft.com/download/dotnet-core) for your operating system.
51+
- An Azure Email Communication Services Resource created and ready with a provisioned domain [Get started with Creating Email Communication Resource](../create-email-communication-resource.md)
52+
- An active Communication Services resource connected with Email Domain and a Connection String. [Get started by Connecting Email Resource with a Communication Resource](../connect-email-communication-resource.md)
53+
54+
Completing this quick start incurs a small cost of a few USD cents or less in your Azure account.
55+
56+
> [!NOTE]
57+
> We can also send an email from our own verified domain. [Add custom verified domains to Email Communication Service](../add-azure-managed-domains.md).
58+
59+
### Prerequisite check
60+
61+
- In a terminal or command window, run the `dotnet` command to check that the .NET client library is installed.
62+
- To view the subdomains associated with your Email Communication Services resource, sign in to the [Azure portal](https://portal.azure.com/), locate your Email Communication Services resource and open the **Provision domains** tab from the left navigation pane.
63+
64+
### Create a new C# application
65+
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**.
66+
67+
```console
68+
dotnet new console -o EmailQuickstart
69+
```
70+
71+
Change your directory to the newly created app folder and use the `dotnet build` command to compile your application.
72+
73+
```console
74+
cd EmailQuickstart
75+
dotnet build
76+
```
77+
78+
### Install the package
79+
While still in the application directory, install the Azure Communication Services Email client library for .NET package by using the `dotnet add package` command.
80+
81+
```console
82+
dotnet add package Azure.Communication.Email
83+
```
84+
85+
## Creating the email client with authentication
86+
87+
Open **Program.cs** and replace the existing code with the following
88+
to add `using` directives for including the `Azure.Communication.Email` namespace and a starting point for execution for your program.
89+
90+
```csharp
91+
using System;
92+
using System.Collections.Generic;
93+
using System.Threading;
94+
using System.Threading.Tasks;
95+
96+
using Azure;
97+
using Azure.Communication.Email;
98+
99+
namespace SendEmail
100+
{
101+
internal class Program
102+
{
103+
static async Task Main(string[] args)
104+
{
105+
106+
}
107+
}
108+
}
109+
```
110+
111+
There are a few different options available for authenticating an email client:
112+
113+
#### [Connection String](#tab/connection-string)
114+
115+
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](../../create-communication-resource.md#store-your-connection-string).
116+
117+
```csharp
118+
// This code demonstrates how to fetch your connection string
119+
// from an environment variable.
120+
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
121+
EmailClient emailClient = new EmailClient(connectionString);
122+
```
123+
124+
#### [Azure Active Directory](#tab/aad)
125+
126+
To authenticate using [Azure Active Directory](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/identity/Azure.Identity), install the `Azure.Identity` library package for .NET by using the `dotnet add package` command.
127+
128+
```console
129+
dotnet add package Azure.Identity
130+
```
131+
Open **Program.cs** in a text editor and replace the body of the `Main` method with code to initialize an `EmailClient` using [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/identity/Azure.Identity#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](../../identity/service-principal.md?pivots=platform-azcli).
132+
133+
```csharp
134+
// This code demonstrates how to authenticate to your Communication Service resource using
135+
// DefaultAzureCredential and the environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID,
136+
// and AZURE_CLIENT_SECRET.
137+
string resourceEndpoint = "<ACS_RESOURCE_ENDPOINT>";
138+
EmailClient emailClient = new EmailClient(new Uri(resourceEndpoint), new DefaultAzureCredential());
139+
```
140+
141+
#### [AzureKeyCredential](#tab/azurekeycredential)
142+
143+
Email clients can also be authenticated using an [AzureKeyCredential](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html#azure.core.credentials.AzureKeyCredential). Both the `key` and the `endpoint` can be founded on the "Keys" pane under "Settings" in your Communication Services Resource.
144+
145+
```csharp
146+
var key = new AzureKeyCredential("<your-key-credential>");
147+
var endpoint = new Uri("<your-endpoint-uri>");
148+
149+
var emailClient = new EmailClient(endpoint, key);
150+
```
151+
152+
---
153+
154+
> [!NOTE]
155+
> It is recommended to use the manual polling (Send Email with asynchronous status polling) to send email.
156+
157+
#### [Send Email with asynchronous status polling](#tab/send-email-and-get-status-async)
158+
159+
[!INCLUDE [polling-net](../send-email-advanced/includes/asynchronous-status-polling-net.md)]
160+
161+
#### [Send Email with synchronous status polling](#tab/send-smail-and-get-status-sync)
162+
163+
## Basic email sending
164+
165+
### Construct your email message
166+
167+
To send an email message, you need to:
168+
- Define the email subject and body.
169+
- Define your Sender Address. Construct your email message with your Sender information you get your MailFrom address from your verified domain.
170+
- Define the Recipient Address.
171+
- Call the SendAsync method. Add this code to the end of `Main` method in **Program.cs**:
172+
173+
Replace with your domain details and modify the content, recipient details as required
174+
```csharp
175+
176+
//Replace with your domain and modify the content, recipient details as required
177+
178+
var subject = "Welcome to Azure Communication Service Email APIs.";
179+
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>";
180+
var sender = "[email protected]";
181+
var recipient = "[email protected]";
182+
183+
```
184+
### Send and get the email send status
185+
186+
To send an email message, you need to:
187+
- Call SendAsync 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.
188+
- SendAsync method returns EmailSendOperation that returns "Succeeded" EmailSendStatus if email is out for delivery and throws an exception otherwise. Add this code to the end of `Main` method in **Program.cs**:
189+
190+
```csharp
191+
try
192+
{
193+
Console.WriteLine("Sending email...");
194+
EmailSendOperation emailSendOperation = await emailClient.SendAsync(
195+
Azure.WaitUntil.Completed,
196+
sender,
197+
recipient,
198+
subject,
199+
htmlContent);
200+
EmailSendResult statusMonitor = emailSendOperation.Value;
201+
202+
Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");
203+
204+
/// Get the OperationId so that it can be used for tracking the message for troubleshooting
205+
string operationId = emailSendOperation.Id;
206+
Console.WriteLine($"Email operation id = {operationId}");
207+
}
208+
catch (RequestFailedException ex)
209+
{
210+
/// OperationID is contained in the exception message and can be used for troubleshooting purposes
211+
Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
212+
}
213+
```
214+
215+
### Getting email delivery status
216+
217+
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:
218+
219+
- Delivered.
220+
- Failed.
221+
- Quarantined.
222+
223+
See [Handle Email Events](../handle-email-events.md) for details.
224+
225+
You can also now subscribe to Email Operational logs that provide information related to delivery metrics for messages sent from the Email service.
226+
227+
- Email Send Mail operational logs - provides detailed information related to the Email service send mail requests.
228+
- Email Status Update operational logs - provides message and recipient level delivery status updates related to the Email service send mail requests.
229+
230+
Access logs for [Email Communication Service](../../../concepts/analytics/logs/email-logs.md).
231+
232+
### Run the code
233+
234+
Run the application from your application directory with the `dotnet run` command.
235+
236+
```console
237+
dotnet run
238+
```
239+
240+
### Sample code
241+
242+
You can download the sample app from [GitHub](https://github.com/Azure-Samples/communication-services-dotnet-quickstarts/tree/main/SendEmail)
243+
244+
---
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
---
2+
title: include file
3+
description: Manual polling .NET SDK include file
4+
author: natekimball-msft
5+
manager: koagbakp
6+
services: azure-communication-services
7+
ms.author: natekimball
8+
ms.date: 04/07/2023
9+
ms.topic: include
10+
ms.service: azure-communication-services
11+
---
12+
13+
## Basic email sending
14+
15+
### Construct your email message
16+
17+
To send an email message, you need to:
18+
- Define the email subject and body.
19+
- Define your Sender Address. Construct your email message with your Sender information you get your MailFrom address from your verified domain.
20+
- Define the Recipient Address.
21+
- Call the SendAsync method. Add this code to the end of `Main` method in **Program.cs**:
22+
23+
Replace with your domain details and modify the content, recipient details as required
24+
```csharp
25+
26+
//Replace with your domain and modify the content, recipient details as required
27+
28+
var subject = "Welcome to Azure Communication Service Email APIs.";
29+
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>";
30+
var sender = "[email protected]";
31+
var recipient = "[email protected]";
32+
33+
```
34+
### Send and get the email send status
35+
36+
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.
37+
38+
The returned EmailSendOperation object contains an EmailSendStatus object that contains:
39+
- Current status of the Email Send operation.
40+
- An error object with failure details if the current status is in a failed state.
41+
42+
```csharp
43+
44+
/// Send the email message with WaitUntil.Started
45+
EmailSendOperation emailSendOperation = await emailClient.SendAsync(
46+
Azure.WaitUntil.Started,
47+
sender,
48+
recipient,
49+
subject,
50+
htmlContent);
51+
52+
/// Call UpdateStatus on the email send operation to poll for the status
53+
/// manually.
54+
try
55+
{
56+
while (true)
57+
{
58+
await emailSendOperation.UpdateStatusAsync();
59+
if (emailSendOperation.HasCompleted)
60+
{
61+
break;
62+
}
63+
await Task.Delay(100);
64+
}
65+
66+
if (emailSendOperation.HasValue)
67+
{
68+
Console.WriteLine($"Email queued for delivery. Status = {emailSendOperation.Value.Status}");
69+
}
70+
}
71+
catch (RequestFailedException ex)
72+
{
73+
Console.WriteLine($"Email send failed with Code = {ex.ErrorCode} and Message = {ex.Message}");
74+
}
75+
76+
/// Get the OperationId so that it can be used for tracking the message for troubleshooting
77+
string operationId = emailSendOperation.Id;
78+
Console.WriteLine($"Email operation id = {operationId}");
79+
```
80+
81+
Run the application from your application directory with the `dotnet run` command.
82+
83+
```console
84+
dotnet run
85+
```
86+
87+
### Sample code
88+
89+
You can download the sample app from [GitHub](https://github.com/Azure-Samples/communication-services-dotnet-quickstarts/tree/main/SendEmailAdvanced/SendEmailWithManualPollingForStatus)

articles/communication-services/quickstarts/email/send-email.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ This quickstart describes how to send email using our Email SDKs.
2828
::: zone-end
2929

3030
::: zone pivot="programming-language-csharp"
31-
[!INCLUDE [Send email with .NET SDK](./includes/send-email-net.md)]
31+
[!INCLUDE [Send email with .NET SDK](./includes/send-email-async-sync-net.md)]
3232
::: zone-end
3333

3434
::: zone pivot="programming-language-javascript"

0 commit comments

Comments
 (0)