Blog Post

AI - Azure AI services Blog
4 MIN READ

Intelligent Email Automation with Azure AI Agent Service

AngelaKunanbaeva's avatar
Jun 03, 2025

In today’s fast-paced digital landscape, automating routine tasks not only saves time but also boosts efficiency and accuracy. One great example of this automation is an intelligent email-sending agent that combines Azure AI Agent Services with Azure Communication Services. In this post, we’ll explore how these tools work together to streamline email automation and elevate everyday workflows.

Do you ever wish you could simply tell your agent to send an email, without the hassle of typing everything — from recipient list to the subject and the body? If so, this guide on building an email-sending agent might be exactly what you’re looking for. Technically, this guide won’t deliver a fully automated agent right out of the box - you’ll still need to add a speech-to-text layer and carefully curate your prompt instructions. By the end of this post, you’ll have an agent capable of interacting with users through natural conversation and generating emails with dynamic subject lines and content.

Overview

Azure AI Agent Services offers a robust framework for building conversational agents, making it an ideal choice for developers seeking enterprise-grade security and compliance. This ensures that your AI applications are both secure and trustworthy. In our case, the agent is designed to send emails by processing user-provided details such as the subject and body of the email. You can learn more about Azure AI Agent Service here.

Azure Communication Services will act as the backbone for sending these emails reliably and securely. You can easily configure your email communication service following this guide.

How It Works

We’ll start by configuring the email communication service as described in the setup guide. To send emails, we’ll use the EmailClient from azure.communication.email library to establish a connection and handle delivery.

To make this functionality available to our AI agent, we’ll wrap the email-sending logic in a FunctionTool and ensure that it conforms to all the requirements outlined here.

The function will be structured as follows:

def azure_send_email(subject: str, body:str) -> dict:
    """
    Sends an email using Azure Communication Services EmailClient.
    This function builds the email message from a default template, modifying only the
    'subject' and 'body' field in the content section. Other parameters remain unchanged.
    Parameters:
        subject (str): The email subject to override.
        body (str): The content of the email.
    Returns:
        dict: A dictionary containing the operation result:
              - On success: {"operationId": <operation_id>, "status": "Succeeded", "message": <success_message>}
              - On failure: {"error": <error_message>}
    Example:
        >>> response = azure_send_email("Hello World")
        >>> print(response)
    """
    try:
        message = DEFAULT_MESSAGE.copy()
        message["content"] = DEFAULT_MESSAGE["content"].copy()
        message["content"]["subject"] = subject
        message["content"]["html"] = "<html><h1>" + body +"</h1></html>"
        email_client = EmailClient.from_connection_string(
            os.getenv("EMAIL_COMMUNICATION_SERVICES_STRING")
        )
        poller = email_client.begin_send(message)
        time_elapsed = 0
        while not poller.done():
            print("Email send poller status: " + poller.status())
            poller.wait(POLLER_WAIT_TIME)
            time_elapsed += POLLER_WAIT_TIME
            if time_elapsed > 18 * POLLER_WAIT_TIME:
                raise RuntimeError("Polling timed out.")
        result = poller.result()
        if result["status"] == "Succeeded":
            success_message = f"Successfully sent the email (operation id: {result['id']})"
            print(success_message)
            return {"operationId": result["id"], "status": result["status"], "message": success_message}
        else:
            error_msg = str(result.get("error", "Unknown error occurred"))
            raise RuntimeError(error_msg)
    except Exception as ex:
        error_str = f"An error occurred: {ex}"
        print(error_str)
        return {"error": error_str}

Next, we’ll create a project in Azure AI Foundry, which will allow us to link our agent to the Foundry workspace and enable tracing and monitoring for enhanced observability. Get the project connection string to connect the services and let’s create our agent.

project_client = AIProjectClient.from_connection_string(
    credential=DefaultAzureCredential(),
    conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
with project_client:
    agent = project_client.agents.create_agent(
        model=os.environ["MODEL_DEPLOYMENT_NAME"],
        name="email-assistant",
        instructions=(
            """
            You are an assistant that sends emails using the send_email function.
            When a request to send an email is received, call the send_email tool and confirm that the email has been sent.
            The function expects two parameters: 'subject' and 'body
            Use the following format as a guide:
            
            {
                "subject": "<New Email Subject>",
                "body": "<Email Body>"
            }
            
            The 'subject' and 'body' value will be provided by the user.
            """
        ),
        tools=functions.definitions,  # Register our custom tool with the agent.
    )

Our agent will reference the email-sending function we defined earlier:

def send_email_function(subject: str, body: str) -> dict:
    """
    Wrapper function for sending an email.
    Expects a single parameter:
        - subject (str): The email subject.
    The function constructs the email using a default template where only the subject
    value is replaced, while all other email details remain unchanged.
    """
    return azure_send_email(subject, body)

And there you have it — your very own automated email-sending agent! You can find the full example in my GitHub repo.

Implementation Considerations

Here are few things to consider:

  • Authentication and Authorization: When integrating Azure Communication Services, it’s important to implement robust security practices. Ensure that your agent properly authenticates requests to avoid unauthorized access.
  • Handling Edge Cases: User conversations can often be unpredictable. Plan for incomplete inputs, ambiguous instructions, or even errors in processing.
  • Logging and Monitoring: Utilize Azure’s monitoring tools to keep track of email dispatches. This allows for quick troubleshooting and ensures the agent is performing as expected.
  • Customization: Depending on your use case, you might want to extend the agent’s capabilities. For instance, handling attachments or integrating with other communication channels is possible with modular application design.

Conclusion

Integrating Azure AI Agent Services with Azure Communication Services unlocks exciting opportunities for automating communication workflows. By creating an agent that can interact with users in natural language and dispatch emails based on user input, organizations can streamline operations, enhance user engagement, and operate more efficiently. Whether it’s for routine notifications or customer support, this intelligent email-sending agent demonstrates the power of transforming everyday business processes.

 

Thank you for your time.

Updated May 19, 2025
Version 1.0
No CommentsBe the first to comment