Quickstart: How to send an email using Azure Communications Service: A quickstart for Azure Communications Services (2023)

  • Article
  • 22 minutes to read

Important

This Azure Communications Services feature is currently in preview.

Visualization APIs and SDKs are provided without a service level agreement. We do not recommend using them for production workloads. Some features may not be supported or have limited capabilities.

For more information, seeSupplemental Terms of Use for Microsoft Azure Previews.

This quickstart shows you how to send email using our email SDKs.

Get started with Azure Communication Services by using the Communication Services C# email client library to send email messages.

There is a small cost to your Azure account for completing this quickstart, a few cents at most.

previous requirements

  • An Azure account with an active subscription.Create a free account.
  • The last version.NET Core-Clientbibliothekfor your operating system.
  • An Azure Email Communication Services resource created and ready with a provided domainStart by creating an email communication resource
  • An active communication services resource associated with an email domain and connection string.Start by connecting an email resource to a communication resource

Check requirement

  • In a terminal or command window, run theNet pointCommand to check if the .NET client library is installed.
  • Sign in to view the subdomains associated with your Email Communications Services featureblue portal, locate the E-mail Communication Services feature and open theprovide domainsTab in the left navigation pane.

Attitude

Create a new C# application

In a console window (such as cmd, PowerShell, or Bash), use thePunktnetz NovoCommand to create a new console application namedEmail Quick Start. This command creates a simple "Hello World" C# project with a single source file:program.cs.

dotnet new console -o quickstart email

Change your directory to the newly created Applications folder and use thebuild dotnetCommand to compile your application.

cd Mail Quickstartdotnet build

Install the package

Also, in the application directory, install the Azure Communications Services email client library for the .NET package usingAdd dotnet packageDomain.

dotnet add package Azure.Communication.Email --prerelease

Open mindedprogram.csand replace the existing code with the following code to adduseInstructions for taking theAzure.CommunicationNamespace and a starting point for running your program.

Using System;Using System.Collections.Generic;Using System.Threading;Using System.Threading.Tasks;Using Azure;Using Azure.Communication.Email;Using Azure.Communication.Email.Models;namespace SendEmail{ inner class Program { static async Hauptaufgabe (String [] Argumente) { } }}

object model

The following classes and interfaces control some of the key features of the Azure Communications Services for C# email client library.

Namedescription
E-Mail-AddresseThis class contains an email address and a display name option.
email notesThis class creates an email attachment by accepting a unique ID, an email attachment type, and a content byte sequence.
customer emailThis class is required for all email functionality. It instantiates it with its connection string and uses it to send email messages.
Email Client OptionsThis class can be added to the EmailClient instantiation to target a specific version of the API.
email contentThis class contains the subject and body of the email message. The importance can also be set in the EmailContent class.
E-MailCustomHeaderThis class allows you to add a name/value pair to a custom header.
Die EmailThis class combines sender, content and receiver. Custom headers, attachments, and reply email addresses can also be added.
Email recipientThis class contains lists of EmailAddress objects for email message recipients, including optional lists for CC and BCC recipients.
SendStateResultThis class contains lists of email message delivery statuses.

Authenticate client

Option 1: Authenticate with a connection string

Open mindedprogram.csin a text editor and replace the body of theDirectorMethod with code to initialize acustomer emailwith your connection string. The following code gets the connection string for the resource from a called environment variableCOMMUNICATION_SERVICES_CONNECTION_STRING. learn howManage your resource's connection string.

// This code demonstrates how to get your connection string // from an environment variable.string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");EmailClient emailClient = new EmailClient(connectionString);

Option 2: Authenticate with Azure Active Directory

To authenticate with Azure Active Directory, install the Azure.Identity for .NET library package with theAdd dotnet packageDomain.

Add dotnet azure.identity package

Open mindedprogram.csin a text editor and replace the body of theDirectorMethod with code to initialize acustomer emailuseAzure default credentials. The Azure Identity SDK reads values ​​from three environment variables at runtime to authenticate the app. learn howCreate an application registered in Azure Active Directory and set environment variables.

// This code shows how to authenticate your communication service resource using // DefaultAzureCredential and the environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, // and AZURE_CLIENT_SECRET.string resourceEndpoint = "<ACS_RESOURCE_ENDPOINT>";EmailClient emailClient = new EmailClient(new Uri ( resourceEndpoint) , new DefaultAzureCredential ());

Send an email

To send an email, you must

  • Create the content and body of the email with EmailContent
  • Add containers
  • Compose your email message with sender information and get your MailFrom address from your verified domain.
  • Specify your email content and recipients and add attachments if necessary
  • Call the Send method. Add this code at the endDirectormethod oneprogram.cs:

Replace them with your domain details and change content and recipient details as needed

//Replace with your domain and change the content, recipient details as needed Service email using the .NET SDK.";List<EmailAddress> emailAddresses = new List<EmailAddress> { new EmailAddress("emailalias@contoso.com ") { DisplayName = "Name of friendly view" }};EmailRecipients emailRecipients = new EmailRecipients (emailAddresses);EmailMessage emailMessage = new EmailMessage("donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net", emailContent, emailRecipients );SendEmailResult emailResult = emailClient.Send (emailMessage,CancellationToken.None);

Get MessageId to track email delivery

To track the email delivery status, you need to get the MessageId of the reply and track the status. If there is no MessageId, repeat the request.

Console.WriteLine($"MessageId = {emailResult.MessageId}");

Get email delivery status

To get the email delivery status, call the GetMessageStatus API with MessageId

Response<SendStatusResult> messageStatus = null;messageStatus = emailClient.GetSendStatus(emailResult.MessageId);Console.WriteLine($"MessageStatus = {messageStatus.Value.Status}");TimeSpan duración = TimeSpan.FromMinutes(3);long start = DateTime.Now.Ticks;do{messageStatus = emailClient.GetSendStatus(emailResult.MessageId); if (messageStatus.Value.Status != SendStatus.Queued) {Console.WriteLine($"MessageStatus = {messageStatus.Value.Status}"); desscanso; } Thread.Sleep(10000); Console.WriteLine($"...");} while (DateTime.Now.Ticks - início <Dauer.Ticks);
state namedescription
I'm in lineThe email has been queued for delivery.
out for deliveryThe email is on its way to its recipients.
droppedThe email message was deleted before delivery could be successfully completed.

Run the code

Run the app from your app directory with theRun dotnetDomain.

Run dotnet

sample code

You can download the sample application belowGitHub

Progressive

Send an email to multiple recipients

We can define multiple recipients by adding additional email addresses to the EmailRecipients object. These addresses can be added asA,CC, ÖCCOrecipient

var toRecipients = new List<EmailAddress>{ new EmailAddress("<emailalias1@emaildomain.com>"), new EmailAddress("<emailalias2@emaildomain.com>"),};var ccRecipients = new List<EmailAddress>{ neue Richtung de correio eletrônico ("<ccemailalias@emaildomain.com>"),};var bccRecipients = new List<EmailAddress>{ new EmailAddress("<bccemailalias@emaildomain.com>"),};EmailRecipients emailRecipients = new EmailRecipients(toRecipients, ccEmpfänger, bccEmpfänger );

You can download the sample app that demonstrates this atGitHub

Send an email with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attached file and base64 encode it.

byte[] bytes = File.ReadAllBytes(filePath);string attachmentFileInBytes = Convert.ToBase64String(bytes);var emailAttachment = new EmailAttachment( "<your-attachment-name>", <EmailAttachmentType>, fileAttachmentInBytes);emailMessage .Attachments.Add (Anexo per E-Mail);

You can download the sample app that demonstrates this atGitHub

Get started with Azure Communication Services using the Communication Services JS email client library to send email messages.

There is a small cost to your Azure account for completing this quickstart, a few cents at most.

previous requirements

  • An Azure account with an active subscription.Create a free account.
  • Node.jsVerse Active LTS und Maintenance LTS.
  • An Azure Email Communication Services resource created and ready with a provided domainStart by creating an email communication resource
  • An active communication services resource associated with an email domain and connection string.Start by connecting an email resource to a communication resource

Check requirement

  • Run in a terminal or command windownode versionto verify that Node.js is installed.
  • Sign in to view domains verified with your email communication service capabilityblue portal, locate the E-mail Communication Services feature and open theprovide domainsTab in the left navigation pane.

Attitude

Create a new Node.js application

First, open your terminal or command window, create a new directory for your application, and navigate to it.

mkdir quickstart email && cd quickstart email

To runnpm initializes -yto create onePackage.jsonFile with default settings.

npm initializes -y

Using a text editor, create a file namedsend-email.jsin the root of the project. Change the "parent" property toPackage.jsonto send-email.js. In the following sections, you'll add all the source code for this quickstart to this file.

Install the package

Use oinstall npmCommand to install Azure Communications Services email client library for JavaScript.

npm install @azure/communication-email --save

Him--to saveOption lists the library as a dependency of yoursPackage.jsonoffice hours.

object model

The following classes and interfaces control some of the key features of the Azure Communication Services JavaScript email client library.

Namedescription
E-Mail-AddresseThis interface includes an email address and an option to display a name.
email notesThis interface creates an email attachment by accepting a unique ID, an email attachment type, and a content byte sequence.
customer emailThis class is required for all email functionality. It instantiates it with its connection string and uses it to send email messages.
Email Client OptionsThis interface can be added to the EmailClient instantiation to target a specific version of the API.
email contentThis interface contains the subject, plain text and HTML of the email message.
E-MailCustomHeaderThis interface allows you to add a name/value pair to a custom header.
Die EmailThis interface combines sender, content and receiver. Optionally, custom headers, importance, attachments, and reply email addresses can also be added.
Email recipientThis interface contains lists of EmailAddress objects for email message recipients, including optional lists for CC and BCC recipients.
SendStateResultThis interface contains the message ID and the delivery status of the email message.

Authenticate client

import thosecustomer emailfrom the client library and instantiate it with your connection string.

The following code gets the connection string for the resource from a called environment variableCOMMUNICATION_SERVICES_CONNECTION_STRINGwith the dotenv package. Use theinstall npmCommand to install dotenv package. learn howManage your resource's connection string.

npm install dotenv

Add the following codesend-email.js:

const { EmailClient } = require("@azure/communication-email");require("dotenv").config(); // This code shows how to get your connection string // from an environment variable. const connectionString = process .env['COMMUNICATION_SERVICES_CONNECTION_STRING'];

Send an email

To send an email, you must

  • Create the content and body of the email with EmailContent
  • Add containers
  • Compose your email message with sender information and get your MailFrom address from your verified domain.
  • Specify your email content and recipients and add attachments if necessary
  • Calling the send method:

Replace them with your domain details and change content and recipient details as needed

async function main() { try { var client = new EmailClient(connectionString); //send mail const emailMessage = { sender: "<donotreply@xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>", content: { subject: "Welcome to Azure Communication Service email", plain text: "< This Email is sent by Azure Communication Service Email using the JS SDK.>" }, recipient: { to: [ { email: "<emailalias@emaildomain.com>", }, ], }, }; var response = wait for client. send (email message); } Capture(e) { console.log(e); }}Director();

Get MessageId to track email delivery

To track the email delivery status, you need to get the MessageId of the reply and track the status. If there is no MessageId, repeat the request.

const messageId = response.mensajeId; if (messageId === null) { console.log("message id not found"); Return; }

Get email delivery status

To get the email delivery status, call the GetMessageStatus API with MessageId

// Check email status, wait 5 seconds, check 60 seconds. leave counter = 0; const statusInterval = setInterval(async() { counter++; try { const response = wait for client.getSendStatus(messageId); if (response) { console.log(`Email Status for ${messageId}: ${response.status }` ); if (response.status.toLowerCase() !== "queued" || counter > 12) { clearInterval(statusInterval); } } } catch (e) { console.log(e); } }, 5000);
state namedescription
I'm in lineThe email has been queued for delivery.
out for deliveryThe email is on its way to its recipients.
droppedThe email message was deleted before delivery could be successfully completed.

Run the code

Use the node command to run the code that you added to the send-email.js file.

es ./send-email.js

sample code

You can download the sample application belowGitHub

Progressive

Send an email to multiple recipients

We can define multiple recipients by adding additional email addresses to the EmailRecipients object. These addresses can be added asA,CC, ÖCCOrecipient

const emailMessage = { Sender: "<donotreply@xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>", content: { Subject: "Welcome to the Azure Communication Service email", plain text: "< This email was sent from Azure Communication Service Email using JS SDK.>" }, recipient: { to: [ { email: "<emailalias@emaildomain.com>" }, { email: "<emailalias2@emaildomain.com > " } ], cc : [ { email: "<ccemailalias@emaildomain.com>" } ], bcc: [ { email: "<bccemailalias@emaildomain.com>" } } ], },};

You can download the sample app that demonstrates this atGitHub

Send an email with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attached file and base64 encode it.

const fs = require("fs"); const ContentAttachment = fs.readFileSync(<Pfad zum Anhang>).toString("base64"); const attachment = { name: "<Name Ihres Anhangs>" , attachmentType : "<your-attachment-type>", contentBytesBase64: attachmentContent,}const emailMessage = { sender: "<donotreply@xxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx .azurecomm.net>“, Inhalt: {Betreff: „Welcome to Azure Communication Service Email.“, plainText: „<This email is sent from Azure Communication Service Email using the JS SDK.>“ }, receivers: { to: [ { email: "<emailalias@emaildomain.com>", }, ], }, Anhänge: [Anhang]};

You can download the sample app that demonstrates this atGitHub

Get started with Azure Communication Services using the Communication Services Java Email SDK to send email messages.

There is a small cost to your Azure account for completing this quickstart, a few cents at most.

previous requirements

  • An Azure account with an active subscription.Create a free account.
  • Java Development Suite (JDK)Version 8 or higher.
  • Specialist Apache.
  • An active Azure Communication Services resource associated with an email domain and its connection string.Start by connecting an email communication resource to an Azure communication resource.

Check requirement

  • Run in a terminal or command windowmvn-vto check if Maven is installed.
  • Sign in to view domains verified with your email communication service capabilityblue portal. Locate the Email Communication Services feature and open itprovide domainsTab in the left navigation pane.

Configure the environment of the application

Follow the steps in the following sections to set up an environment for sending email.

Create a new Java application

Open your terminal or command window and navigate to the directory where you want to build your Java application. Run the following command to create the Java project from the maven-archetype-quickstart template.

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

Himto generatetarget creates a directory with the same name as theartefactoIdValue. Under this directory, thesrc/principal/javaDirectory contains the source code of the project thatsrc/test/java directorycontains the test source and thepom.xmlThe file is the Project Object Model (POM) of the project.

Install the package

open thispom.xmlfile in your text editor. Add the following dependency item to the dependency group.

<dependency> <groupId>com.azure</groupId> <artifactId>azure-communication-email</artifactId> <version>1.0.0-beta.1</version></dependency>

Configure the application structure

Open minded/src/main/java/com/communication/quickstart/App.javaIn a text editor, add and remove import statementsSystem.out.println("¡Hallo Welt!");Expression:

Paket com.communication.quickstart;import com.azure.communication.email.models.*;import com.azure.communication.email.*;import java.util.ArrayList;public class App{ public static void main( String[] args ) { // O código de início rápido vai aqui. }}

object model

The following classes and interfaces handle some of the key features of the Azure Communication Services Email SDK for Python.

Namedescription
E-Mail-AddresseThis interface includes an email address and an option to display a name.
email notesThis interface creates an email attachment by accepting a unique ID, an email attachment type, and a content byte sequence.
customer emailThis class is required for all email functionality. It instantiates it with its connection string and uses it to send email messages.
Email Client OptionsThis interface can be added to the EmailClient instantiation to target a specific version of the API.
email contentThis interface contains the subject, plain text and HTML of the email message.
E-MailCustomHeaderThis interface allows you to add a name/value pair to a custom header.
Die EmailThis interface combines sender, content and receiver. Optionally, custom headers, importance, attachments, and reply email addresses can also be added.
Email recipientThis interface contains lists of EmailAddress objects for email message recipients, including optional lists for CC and BCC recipients.
SendStateResultThis interface contains the message ID and the delivery status of the email message.

Authenticate client

To authenticate a client, create an instancecustomer emailwith your connection string. learn howManage your resource's connection string. You can also initialize the client with any custom HTTP client that implements thecom.azure.core.http.HttpClientInterface.

To instantiate a client, add the following codeDirectorMethod:

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

This quickstart uses connection strings for simplicity, but we recommend using them in production environmentsservice manager.

Send an email

To send an email, you must

  • Create email content
  • Create an email address for the recipient
  • Create the email recipients
  • Compose the email message using the email body, email address, and sender information from your verified domain's MailFrom address
  • call sending method
EmailContent content = new EmailContent("Bienvenido al correo eletronico of Azure Communication Services") .setPlainText("Esta message of correio eletronico é enviada de Azure Communication Services Email usando o SDK of Python.");EmailAddress emailAddress = new EmailAddress("< emailalias@emaildomain.com >");ArrayList<EmailAddress> addressList = new ArrayList<>();addressList.add(emailAddress);EmailRecipients emailRecipients = new EmailRecipients(addressList);EmailMessage emailMessage = new EmailMessage( "<donotreply@xxxxxxxx- xxxx-xxxx-xxxx -xxxxxxxxxxxx.azurecomm.net>", content, emailRecipients);SendEmailResult respuesta = emailClient.send(emailMessage);

Make these substitutions in your code:

  • Substitute<aliasdecorreoelectrónico@dominiodecorreoelectrónico.com>with the email address you want to send a message to.
  • Substitute<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>with the MailFrom address of your verified domain.

Retrieve message ID from email delivery

To track the delivery status of your email, you need theMessage IDThe answer

String message_id = respuesta.getMessageId();

Get email delivery status

We can still check the email delivery status until the status isout for delivery.

long wait time = 120 * 1000; tempo limite booleano = verdadeiro; while (waitTime > 0){ SendStatusResult sendStatus = emailClient.getSendStatus(messageId); System.out.printf("Send email status for MessageId: <{%s}>, Status: [{%s}]", messageId, sendStatus.getStatus()); if (!sendStatus.getStatus().toString().toLowerCase().equals(SendStatus.QUEUED.toString())) { speed limit = false; desscanso; } Thread.sleep(10000); waitTime = waitTime-10000;}if(waittime){ System.out.println("Wait time or email expiration");}
state namedescription
I'm in lineThe email has been queued for delivery.
out for deliveryThe email is on its way to its recipients.
droppedThe email message was deleted before delivery could be successfully completed.

Run the code

  1. Navigate to the directory containing thepom.xmlarchive and compile the project with themvnDomain.

    compile mvn
  2. Build the package.

    mvn Package
  3. do the followingmvnCommand to run the application.

    mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false

sample code

You can download the sample application belowGitHub

Progressive

Send an email to multiple recipients

We can define multiple recipients by adding additional email addresses to the EmailRecipients object. These addresses can be added asA,CC, ÖCCOrecipient

EmailAddress toEmailAddress1 = new EmailAddress("<emailalias1@emaildomain.com>");EmailAddress toEmailAddress2 = new EmailAddress("<emailalias2@emaildomain.com>");EmailAddress ccEmailAddress = new EmailAddress("<ccemailalias@emaildomain.com>") ;EmailAddress bccEmailAddress = new EmailAddress("<bccemailalias@emaildomain.com>");ArrayList<EmailAddress> toAddressList = new ArrayList<>();toAddressList.add(toEmailAddress1);toAddressList.add(toEmailAddress2);ArrayList<EmailAddress> ccAddressList = neue ArrayList<>();ccAddressList.add(ccEmailAddress);ArrayList<EmailAddress> bccAddressList = neue ArrayList<>();bccAddressList.add(bccEmailAddress);EmailRecipients emailRecipients = new EmailRecipients(toAddressList) .setCc(ccAddressList) .setBcc (bccListaDirectiones);

You can download the sample app that demonstrates this atGitHub

Send an email with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attached file and base64 encode it.

Datei file = new File("<seu-caminho-do-attachment>");byte[] fileContent = null;try { fileContent = Files.readAllBytes(file.toPath());} catch (Exception e) { System. aus. println(e);}String b64file = Base64.getEncoder().encodeToString(fileContent);EmailAttachment adjunto = new EmailAttachment("<su-nombre-de-archivo-adjunto>", "<su-tipo-de-archivo- adjunto>", b64file) ;ArrayList<EmailAttachment> AttachmentList = new ArrayList<>();attachmentList.add(adjunto);EmailMessage emailMessage = new EmailMessage("<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net >", conteúdo) . setRecipients(emailRecipients) .setAttachments(attachmentList);

You can download the sample app that demonstrates this atGitHub

Get started with Azure Communication Services using the Communication Services Python Email SDK to send email messages.

There is a small cost to your Azure account for completing this quickstart, a few cents at most.

previous requirements

  • An Azure account with an active subscription.Create a free account.
  • Python3,7+.
  • An Azure Email Communication Services resource created and ready with a provided domain.Start by creating an email communication resource.
  • An active Azure Communication Services resource associated with an email domain and its connection string.Start by connecting an email communication resource to an Azure communication resource.

Check requirement

  • In a terminal or command window, run thepython --versionCommand to check if Python is installed.
  • Sign in to view domains verified with your email communication service capabilityblue portal. Locate the Email Communication Services feature and open itprovide domainsTab in the left navigation pane.

Configure the environment of the application

Follow the steps in the following sections to set up an environment for sending email.

Create a new Python application

  1. Open your terminal or command window. Then use the following command to create and navigate to a new directory for your app.

    mkdir quickstart email && cd quickstart email
  2. Using a text editor, create a file namedenviar-email.pyin the root of the project and add the structure of the program, including basic exception handling.

    import osfrom azure.communication.email import EmailClienttry: # quickstart code goes here.except exception like ex: print('Exception:') print(ex)

In the following sections, you'll add all of the source code for this quickstartenviar-email.pyfile you just created.

Install the package

Still in the application directory, install the Azure Communications Services Email SDK package for Python with the following command.

pip install azure-communication-email

object model

The following classes and interfaces cover some of the key features of the Azure Communication Services SMS SDK for Python.

Namedescription
E-Mail-AddresseThis interface includes an email address and an option to display a name.
email notesThis interface creates an email attachment by accepting a unique ID, an email attachment type, and a content byte sequence.
customer emailThis class is required for all email functionality. It instantiates it with its connection string and uses it to send email messages.
Email Client OptionsThis interface can be added to the EmailClient instantiation to target a specific version of the API.
email contentThis interface contains the subject, plain text and HTML of the email message.
E-MailCustomHeaderThis interface allows you to add a name/value pair to a custom header.
Die EmailThis interface combines sender, content and receiver. Optionally, custom headers, importance, attachments, and reply email addresses can also be added.
Email recipientThis interface contains lists of EmailAddress objects for email message recipients, including optional lists for CC and BCC recipients.
SendStateResultThis interface contains the message ID and the delivery status of the email message.

Authenticate client

instantiieren acustomer emailwith your connection string. learn howManage your resource's connection string.

# Create the EmailClient object that you will use to send email messages.email_client = EmailClient.from_connection_string(<connection_string>)

This quickstart uses connection strings for simplicity, but we recommend using them in production environmentsservice manager.

Send an email

To send an email, you must

  • Create email content
  • Create an email address for the recipient
  • Create the email recipients
  • Compose the email message using the email body, email address, and sender information from your verified domain's MailFrom address
  • call sending method
content = EmailContent( subject="Welcome to Azure Communications Services Email", plain_text="This email is sent from Azure Communications Services Email using the Python SDK.")address = EmailAddress(email="<emailalias@emaildomain.com> ")recipient = EmailRecipients(to=[address])message = EmailMessage( sender="<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>", content=content, Empfänger=Empfänger)response = email_client. Nachricht senden)

Make these substitutions in your code:

  • Substitute<aliasdecorreoelectrónico@dominiodecorreoelectrónico.com>with the email address you want to send a message to.
  • Substitute<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net>with the MailFrom address of your verified domain.

Retrieve message ID from email delivery

To track the delivery status of your email, you need theMessage IDThe answer

message_id = reply.message_id

Get email delivery status

We can still check the email delivery status until the status isout for delivery.

counter = 0while True: counter+=1 send_status = client.get_send_status(message_id) if (send_status): print(f"O status do e-mail para message_id {message_id} é {send_status.status}.") if (send_status.status .lower( ) == "queued" and count < 12): time.sleep(10) # 10 Sekunden vor der Überprüfung vor dem nächsten Schritt. counter +=1 else: if(send_status.status.lower() == "fora da entrega"): print(f"E-Mail-Eintrag para message_id {message_id}.") break else: print("Parece fora do tempo limite de entrega para marque Enviar e-mail de status").
state namedescription
I'm in lineThe email has been queued for delivery.
out for deliveryThe email is on its way to its recipients.
droppedThe email message was deleted before delivery could be successfully completed.

Run the code

Run the app from your app directory with thePythonDomain.

python enviar-email.py

sample code

You can download the sample application belowGitHub

Progressive

Send an email to multiple recipients

We can define multiple recipients by adding additional email addresses to the EmailRecipients object. These addresses can be added asA,CC, ÖCCOrecipient

to_address_1 = EmailAddress(email="<emailalias1@emaildomain.com>")to_address_2 = EmailAddress(email="<emailalias2@emaildomain.com>")cc_address = EmailAddress(email="<ccemailalias@emaildomain.com>")bcc_address = EmailAddress(email="<bccemailalias@emaildomain.com>")recipient = EmailRecipients(to=[to_address_1, to_address_2], cc=[cc_address], bcc=[bcc_address])

You can download the sample app that demonstrates this atGitHub

Send an email with attachments

We can add an attachment by defining an EmailAttachment object and adding it to our EmailMessage object. Read the attached file and base64 encode it. Decode the bytes as a string and pass it to the EmailAttachment object.

import base64with open("<your-attachment-path>", "rb") como arquivo: file_bytes = file.read()file_bytes_b64 = base64.b64encode(file_bytes)attachment = EmailAttachment( name="<your-attachment-name> ", attachment_type="<su-tipo-de-arquivo-adjunto>", content_bytes_base64=file_bytes_b64.decode())message = EmailMessage( sender="<donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net> ", content=conteúdo, destinatarios=destinatarios, arquivos adjuntos=[arquivo adjunto])

You can download the sample app that demonstrates this atGitHub

Troubleshooting

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

clean resources

If you want to clean up and delete a Communication Services subscription, you can delete the resource or resource group. If you delete the resource group, all other resources associated with it are also deleted. learn more aboutresource cleanup.

Next Steps

In this quickstart you learned how to send email using Azure Communications Services.

You might also want:

  • to learnEmail Concepts
  • become acquainted withEmail Client Library

References

Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated: 30/11/2023

Views: 5644

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.