|
| 1 | +--- |
| 2 | +title: Send email with SMTP and XOAuth2 using .NET |
| 3 | +titleSuffix: An Azure Communication Services article |
| 4 | +description: This article describes how to use SMTP and OAuth to send emails to Email Communication Services. |
| 5 | +author: ddouglas-msft |
| 6 | +services: azure-communication-services |
| 7 | +ms.author: ddouglas |
| 8 | +ms.date: 10/18/2023 |
| 9 | +ms.topic: quickstart |
| 10 | +ms.service: azure-communication-services |
| 11 | +ms.custom: devx-track-dotnet |
| 12 | +--- |
| 13 | +# Send email with SMTP and XOAuth2 using .NET |
| 14 | + |
| 15 | +This article describes how to use XOAuth2 for authentication when sending emails using the Simple Mail Transfer Protocol (SMTP) and Azure Communication Services. |
| 16 | + |
| 17 | +## Prerequisites |
| 18 | + |
| 19 | +- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F). |
| 20 | +- The latest version [.NET Core client library](https://dotnet.microsoft.com/download/dotnet-core) for your operating system. |
| 21 | +- An Azure Communication Email Resource created and ready with a provisioned domain [Get started with Creating Email Communication Resource](../create-email-communication-resource.md). |
| 22 | +- An active Azure 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). |
| 23 | +- SMTP credentials created using a Microsoft Entra ID application with access to the Azure Communication Services Resource. [How to create authentication credentials for sending emails using SMTP](smtp-authentication.md). |
| 24 | + |
| 25 | +Completing this example incurs a small cost of a few USD cents or less in your Azure account. |
| 26 | + |
| 27 | +> [!NOTE] |
| 28 | +> You can also send an email from your own verified domain. See [Add custom verified domains to Email Communication Service](../add-azure-managed-domains.md). |
| 29 | +
|
| 30 | +This article describes how to send email with Azure Communication Services using SMTP. |
| 31 | + |
| 32 | +### Prerequisite check |
| 33 | + |
| 34 | +- In a terminal or command window, run the `dotnet` command to check that the .NET client library is installed. |
| 35 | +- To view the subdomains associated with your Azure Communication Email Resource, sign in to the [Azure portal](https://portal.azure.com/), locate your Azure Communication Email Resource and open the **Provision domains** tab from the left navigation pane. |
| 36 | + |
| 37 | +### Create a new C# application |
| 38 | +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**. |
| 39 | + |
| 40 | +```console |
| 41 | +dotnet new console -o EmailSmtpQuickstart |
| 42 | +``` |
| 43 | + |
| 44 | +Change your directory to the newly created app folder and use the `dotnet build` command to compile your application. |
| 45 | + |
| 46 | +```console |
| 47 | +cd EmailSmtpQuickstart |
| 48 | +dotnet build |
| 49 | +``` |
| 50 | + |
| 51 | +Add the MailKit package. |
| 52 | + |
| 53 | +```console |
| 54 | +dotnet add package MailKit |
| 55 | +``` |
| 56 | + |
| 57 | +### Retrieve an Entra token for SMTP OAuth authentication |
| 58 | + |
| 59 | +Complete the following steps to retrieve a Microsoft Entra ID token. Replace the Microsoft Entra ID application details with the values from the Entra application used to create the SMTP Username. |
| 60 | + |
| 61 | +```csharp |
| 62 | +using MailKit.Net.Smtp; |
| 63 | +using MailKit.Security; |
| 64 | +using Microsoft.Identity.Client; |
| 65 | +using MimeKit; |
| 66 | +using System.Net; |
| 67 | + |
| 68 | +// Microsoft Entra ID (Azure AD) credentials |
| 69 | +string smtpUsername = "<SMTP Username of the ACS Resource>"; |
| 70 | +string entraAppId = "<Entra Application ID>"; |
| 71 | +string entraAppClientSecret = "<Entra Application Client Secret>"; |
| 72 | +string tenantId = "<Entra Tenant ID>"; |
| 73 | +string entraAuthority = "https://login.microsoftonline.com/common/"; |
| 74 | + |
| 75 | +// Build the MSAL confidential client application |
| 76 | +IConfidentialClientApplication app = ConfidentialClientApplicationBuilder |
| 77 | + .Create(entraAppId) |
| 78 | + .WithClientSecret(entraAppClientSecret) |
| 79 | + .WithAuthority(new Uri(entraAuthority)) |
| 80 | + .WithTenantId(tenantId) |
| 81 | + .Build(); |
| 82 | + |
| 83 | +// Define the resource scope |
| 84 | +string[] scopes = new string[] { "https://communication.azure.com/.default" }; |
| 85 | + |
| 86 | +// Acquire token for the client |
| 87 | +AuthenticationResult result = await app.AcquireTokenForClient(scopes) |
| 88 | + .ExecuteAsync(); |
| 89 | + |
| 90 | +string token = result.AccessToken; |
| 91 | +``` |
| 92 | + |
| 93 | +### Construct your email message |
| 94 | +To construct an email message, you need to: |
| 95 | +- Define the Email Subject and Body. |
| 96 | +- Define your Sender Address. You get your MailFrom Address from your Verified Domain. |
| 97 | +- Define the Recipient Address. |
| 98 | + |
| 99 | +Replace with your domain details and modify the content, recipient details as required |
| 100 | + |
| 101 | +```csharp |
| 102 | +string smtpHostUrl = "smtp.azurecomm.net"; |
| 103 | +string senderAddress = "<Mailfrom Address>"; |
| 104 | +string recipientAddress = "<Recipient Email Address>"; |
| 105 | + |
| 106 | +string subject = "Welcome to Azure Communication Service Email SMTP"; |
| 107 | +string body = "This email message is sent from Azure Communication Service Email using SMTP."; |
| 108 | +``` |
| 109 | + |
| 110 | + |
| 111 | +### Send an email using MailKit. |
| 112 | + |
| 113 | +```csharp |
| 114 | +var message = new MimeMessage(); |
| 115 | +message.From.Add(new MailboxAddress("Sender Name", senderAddress)); |
| 116 | +message.To.Add(new MailboxAddress("Recipient Name", recipientAddress)); |
| 117 | +message.Subject = subject; |
| 118 | +message.Body = new TextPart("plain") |
| 119 | +{ |
| 120 | + Text = body |
| 121 | +}; |
| 122 | + |
| 123 | +using (var client = new SmtpClient()) |
| 124 | +{ |
| 125 | + client.Connect(smtpHostUrl, 587, SecureSocketOptions.StartTls); |
| 126 | + |
| 127 | + // Use the access token to authenticate |
| 128 | + var oauth2 = new SaslMechanismOAuth2(smtpUsername, token); |
| 129 | + client.Authenticate(oauth2); |
| 130 | + |
| 131 | + client.Send(message); |
| 132 | + client.Disconnect(true); |
| 133 | +} |
| 134 | +``` |
0 commit comments