Blog Post

Azure Communication Services Blog
3 MIN READ

Send an email in Python using Azure Communication Services

MilanKaur's avatar
MilanKaur
Icon for Microsoft rankMicrosoft
Nov 06, 2024

Here is a step-by-step tutorial on how to send an email using the Azure Communication Services SDK in Python. 


Pre-requisites 

1. Azure Subscription – If you don’t have one, create a free account at Azure. 

2. Python – Ensure you have Python 3.6+ installed on your machine. 

 

Setting up Azure resources 

Step 1: Create an Azure Communication Services Resource 

First, you need to create an Azure Communication Services Resource. Follow the instructions at Create Azure Communication Services resource to get started. Copy the connection string from the Keys blade of your communication resource. You'll need it later. 

Step 2: Create an Email Service 

Next, create an Email Service by following the steps at Create and manage Email Communication Service resources using the portal. This is how the create page looks like in the Azure portal.

 

 

 

Step 3: Set Up a Free Azure Subdomain 

Back in the Communication resource, select Try Email. Under Select a domain, choose Set up a free Azure subdomain and select the email service you just created.

  

Use the "Try Email" feature to ensure that your setup is working correctly. Copy and save the Send email from address (it starts with donotreply). You'll need it later.  

 

 

Step 4: Get the connection string and email domain from the Azure portal 

To send an email, you need to set up an Azure Communication Services resource and fetch the connection string. You can do this through the Azure portal: 

  1. Navigate to the Azure Portal. 
  2. Open the Azure Communication Services resource you created in Step 2. 
  3. Go to Settings > Keys and copy the connection string. 
  4. Go to Email Service resource > Domains > Copy the sender address. Or you can use the address you copied in Step 2 when setting up the Azure resources. 
     

Application code to send an Email 

Step 1: Install Required Packages 

First, let's install the required Python packages for Azure Communication Service Email. Open a terminal window on your desktop. Or in VS Code, press Ctrl + ` (press the control key and back quote at the same time) to open a terminal window in the app. 

In the terminal window, run the following command.   

pip install azure-communication-email 

 

Step 2: Create a new Python file. 

Open VS Code or any other IDE of your choice. Create a new Python file named send-email.py. 

 

 Step 3: Write the Python Code to Send an Email 

1. Import the Required Libraries

import os from azure.communication.email  
import EmailClient   

 2. Initialize the Email Client

Use the connection string you fetched earlier to initialize the EmailClient in your Python application. 

connection_string = "your_acs_connection_string"  # Replace with your ACS connection string 
email_client = EmailClient.from_connection_string(connection_string) 

 

3. Prepare the Email Message

Next, construct the email message with subject, content, sender, and recipient details. 

message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "<html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {
                "address": "customer@domain.com",
                "displayName": "Customer Name"
            }
        ]
    },
    "senderAddress": "sender@contoso.com"
}

poller = email_client.begin_send(message)
result = poller.result()


4. Track the Status of the Email (Optional)

You can track the status of the sent email using the message_id returned by the send() method. Here’s how you can query the status of the email: 

def check_email_status(message_id): 
    try: 
        status_response = email_client.get_send_status(message_id) 
        print(f"Email status: {status_response.status}") 
    except HttpResponseError as ex: 
        print(f"Failed to get email status: {ex}") 
 
# Example usage 
message_id = "your_message_id_here" 
check_email_status(message_id) 

 

Step 5: Run the Application 

Once you have set everything up, you can run your Python script, and the email should be sent successfully.  Run the following command in the terminal. 

python send-email.py 

 

Step 6: Debugging and Error Handling 

You might encounter errors such as unverified domains, incorrect connection strings, or issues with the Azure Communication Services setup in the terminal. 
 

Conclusion 

You successfully sent an email using Azure Communication Services in Python! 

This tutorial covered the basic steps, including setting up Azure Communication Services, initializing the EmailClient, and sending an email.  Here are some additional learning resources - 

Updated Nov 06, 2024
Version 3.0
No CommentsBe the first to comment