Send Bulk Emails Using Azure Batch, Azure Functions, Azure Communication Services& Python – Step-by-Step Guide


Here’s a complete end-to-end guide on how to send bulk emails using Azure Batch, Azure Functions, Python, and Azure Communication Services (ACS).


Overview

This guide covers:
✅ Using Azure Functions to trigger bulk email processing
✅ Using Azure Batch for parallel processing of emails
✅ Using Azure Communication Services (ACS) to send emails
✅ Storing email lists in Azure Blob Storage
✅ Implementing everything in Python


Prerequisites

Make sure you have the following:
✔️ Azure Subscription
✔️ Azure Batch Account
✔️ Azure Storage Account (for storing email lists)
✔️ Azure Communication Services (ACS) Email setup
✔️ Python 3.8+ installed
✔️ Azure Functions Core Tools


Step 1: Set Up Azure Communication Services (ACS) Email

1️⃣ Create an ACS Resource:

  • Go to Azure PortalAzure Communication ServicesCreate a new resource
  • Copy the Connection String from the Keys section

2️⃣ Enable Email Communication:

  • Go to the Email section in ACS
  • Configure a verified email sender domain
  • Get the SMTP username & password

Step 2: Create an Azure Function to Trigger Bulk Email Processing

Install Required Libraries

pip install azure-functions azure-storage-blob requests

Create a Python Function in Azure Functions

func init BulkEmailFunction --python
cd BulkEmailFunction
func new --name TriggerEmailProcessing --template "HTTP trigger" --authlevel "function"

Modify TriggerEmailProcessing/__init__.py

import os
import json
import logging
import azure.functions as func
from azure.storage.blob import BlobServiceClient
import requests

# Environment Variables
STORAGE_CONNECTION_STRING = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
ACS_EMAIL_URL = "https://<your-acs-resource>.communication.azure.com/emails:send"
ACS_ACCESS_KEY = os.getenv("ACS_ACCESS_KEY")
CONTAINER_NAME = "emails"

def fetch_email_list():
    """Fetches email list from Azure Blob Storage."""
    blob_service_client = BlobServiceClient.from_connection_string(STORAGE_CONNECTION_STRING)
    blob_client = blob_service_client.get_blob_client(container=CONTAINER_NAME, blob="email_list.json")
    email_data = json.loads(blob_client.download_blob().readall())
    return email_data

def send_email(recipient_email, subject, content):
    """Sends email using Azure Communication Services."""
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {ACS_ACCESS_KEY}"
    }
    payload = {
        "senderAddress": "your-email@yourdomain.com",
        "recipients": {
            "to": [{"address": recipient_email}]
        },
        "content": {
            "subject": subject,
            "plainText": content
        }
    }
    response = requests.post(ACS_EMAIL_URL, headers=headers, json=payload)
    return response.status_code

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info("Triggering bulk email processing...")

    email_list = fetch_email_list()
    for email in email_list:
        send_email(email["email"], email["subject"], email["content"])

    return func.HttpResponse("Emails sent successfully!", status_code=200)

Deploy Function to Azure

func azure functionapp publish <YOUR_FUNCTION_APP_NAME>

Step 3: Set Up Azure Batch for Parallel Email Processing

Create a Python Script for Azure Batch Processing (batch_email_task.py)

import os
import json
import sys
import requests

# Environment Variables
ACS_EMAIL_URL = "https://<your-acs-resource>.communication.azure.com/emails:send"
ACS_ACCESS_KEY = os.getenv("ACS_ACCESS_KEY")

def send_email(email, subject, content):
    """Sends email using Azure Communication Services."""
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {ACS_ACCESS_KEY}"
    }
    payload = {
        "senderAddress": "your-email@yourdomain.com",
        "recipients": {
            "to": [{"address": email}]
        },
        "content": {
            "subject": subject,
            "plainText": content
        }
    }
    response = requests.post(ACS_EMAIL_URL, headers=headers, json=payload)
    return response.status_code

if __name__ == "__main__":
    email_data_file = sys.argv[1]  # Pass email list JSON as an argument
    with open(email_data_file, "r") as file:
        email_list = json.load(file)
    
    for email in email_list:
        send_email(email["email"], email["subject"], email["content"])
    
    print("Batch email processing complete.")

Upload batch_email_task.py to Azure Storage

az storage blob upload --account-name <STORAGE_ACCOUNT> --container-name batchscripts --name batch_email_task.py --file batch_email_task.py

Step 4: Create and Submit an Azure Batch Job

Install Azure Batch SDK

pip install azure-batch

Create a Python Script for Submitting Batch Jobs (submit_batch_job.py)

from azure.batch import BatchServiceClient
from azure.batch.batch_auth import SharedKeyCredentials
from azure.batch.models import PoolInformation, TaskAddParameter, TaskContainerSettings

# Azure Batch Credentials
BATCH_ACCOUNT_NAME = "<YOUR_BATCH_ACCOUNT_NAME>"
BATCH_ACCOUNT_KEY = "<YOUR_BATCH_ACCOUNT_KEY>"
BATCH_ACCOUNT_URL = f"https://{BATCH_ACCOUNT_NAME}.batch.azure.com"
STORAGE_ACCOUNT_NAME = "<YOUR_STORAGE_ACCOUNT_NAME>"
STORAGE_CONTAINER_NAME = "batchscripts"
EMAIL_LIST_BLOB = "email_list.json"

credentials = SharedKeyCredentials(BATCH_ACCOUNT_NAME, BATCH_ACCOUNT_KEY)
batch_client = BatchServiceClient(credentials, batch_url=BATCH_ACCOUNT_URL)

# Create a Batch Job
job_id = "bulk-email-job"
batch_client.job.add(job_id=job_id, pool_info=PoolInformation(pool_id="mypool"))

# Add a Task to the Job
task = TaskAddParameter(
    id="email-task",
    command_line=f"/bin/bash -c 'python3 batch_email_task.py {EMAIL_LIST_BLOB}'",
    container_settings=TaskContainerSettings(image_name="python:3.8")
)
batch_client.task.add(job_id=job_id, task=task)

print("Task submitted to Azure Batch")

Run the Script to Submit a Batch Job

python submit_batch_job.py

Step 5: Monitor and Troubleshoot

Check Batch Job Status

az batch job show --job-id bulk-email-job --account-name <YOUR_BATCH_ACCOUNT_NAME>

View Azure Function Logs

func azure functionapp logstream <YOUR_FUNCTION_APP_NAME>

Check Azure Batch Task Logs

az batch task list --job-id bulk-email-job --account-name <YOUR_BATCH_ACCOUNT_NAME>

Conclusion

🚀 Azure Functions triggers bulk email processing
🚀 Azure Batch parallelizes email sending
🚀 Azure Communication Services (ACS) ensures email delivery
🚀 Azure Blob Storage manages email lists

This solution is scalable, cost-effective, and efficient for bulk email delivery using Azure services.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example