Send emails with an AI agent

AI agents usually return the generated result in Terminal or a chat interface. But there are times when you might prefer to receive the result in an email. Or you might want to send the result to someone else via email.

Scenario

Send Email Flowchart

In this simple example, our AI agent will make up a haiku about dreams and send it to a recipient via a Gmail account, using our silanthro/send-gmail tool.

The send_gmail function takes the following arguments, which will be extracted from our request or generated by the AI agent:

  • subject (str): The subject header of the email
  • body (str): The contents of the email
  • recipients (list[str]): A list of recipient email addresses

It then sends the email and returns:

  • A string, "Email sent successfully"

Setup

To get started, we first set the following environment variables in a .env file:

  • GMAIL_ADDRESS: The sender's email
  • GMAIL_PASSWORD: The sender's app password, not account password
  • GMAIL_DISPLAY_NAME (optional): The sender's display name
  • <COMPANY>_API_KEY: The API key of the model you want to use

Now, we are ready to load the send-gmail tool and build our AI agent.

Scripts

Here are the scripts for the various major LLM providers and frameworks. Remember to install the required dependencies mentioned at the top of each script.

import os
import anthropic
from dotenv import load_dotenv
import stores

# Load environment variables
load_dotenv()

# Load tools and set the required environment variables
index = stores.Index(
    ["silanthro/send-gmail"],
    env_var={
        "silanthro/send-gmail": {
            "GMAIL_ADDRESS": os.environ["GMAIL_ADDRESS"],
            "GMAIL_PASSWORD": os.environ["GMAIL_PASSWORD"],
        },
    },
)

# Get response from the model
client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Send a haiku about dreams to email@example.com"}
    ],
    # Pass tools
    tools=index.format_tools("anthropic"),
)

tool_call = response.content[-1]
# Execute tool call
result = index.execute(tool_call.name, tool_call.input)
print(f"Tool output: {result}")

In the folder where you have this script, you can run the AI agent with the command:

python send-email.py

The recipient should then receive an email with the haiku about dreams.

If you have any questions, let us know on GitHub.