Azure Communication Email

1.1.0 · active · verified Fri Apr 10

The `azure-communication-email` Python client library is part of the Azure Communication Services SDK, enabling developers to integrate email sending capabilities into their applications. It allows sending emails to single or multiple recipients, with support for plain text and HTML content, and attachments. This library helps manage email delivery status and is currently at version 1.1.0, with ongoing development as part of the broader Azure SDK for Python.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates sending a basic email using a connection string for authentication. For production scenarios, it is recommended to use Azure Active Directory authentication via `DefaultAzureCredential` from the `azure-identity` library. Ensure your Communication Services resource, Email Communication Services resource, and a verified domain are configured in Azure.

import os
from azure.communication.email import EmailClient
from azure.identity import DefaultAzureCredential

try:
    # Authenticate using a connection string from an environment variable
    # Alternatively, use DefaultAzureCredential for Azure AD authentication
    connection_string = os.environ.get("ACS_CONNECTION_STRING", "")
    if connection_string:
        email_client = EmailClient.from_connection_string(connection_string)
    else:
        # Requires azure-identity to be installed: pip install azure-identity
        # And environment variables like AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET set
        email_client = EmailClient(endpoint="https://<your-acs-resource-name>.communication.azure.com", credential=DefaultAzureCredential())

    # Replace with your actual sender and recipient addresses
    sender_address = os.environ.get("SENDER_EMAIL_ADDRESS", "donotreply@yourverifieddomain.com")
    recipient_address = os.environ.get("RECIPIENT_EMAIL_ADDRESS", "recipient@example.com")

    message = {
        "senderAddress": sender_address,
        "recipients": {
            "to": [{"address": recipient_address}],
        },
        "content": {
            "subject": "Hello from Azure Communication Email",
            "plainText": "This is the plain text body of the email.",
            "html": "<html><h1>Hello!</h1><p>This is the <b>HTML</b> body.</p></html>"
        }
    }

    print("Sending email...")
    poller = email_client.begin_send(message)
    send_result = poller.result()

    if send_result:
        print(f"Email sent successfully with ID: {send_result['id']}")
    else:
        print("Email sending failed or result is None.")

except Exception as ex:
    print(f"Error sending email: {ex}")

view raw JSON →