AgentMail Python Library
The AgentMail Python library provides convenient access to the AgentMail APIs, an API-first email platform designed for AI agents. It allows programmatic creation and management of email inboxes, sending/receiving emails, and handling email-based workflows with webhooks and real-time events. The library is currently at version 0.4.15 and receives frequent updates, indicating an active development cadence.
Warnings
- gotcha API Key Management: AgentMail requires an `api_key` for authentication. Storing API keys directly in code is insecure. It's best practice to use environment variables (e.g., via `python-dotenv`) for secure access.
- gotcha Error Handling: The SDK raises `agentmail.core.api_error.ApiError` for non-success (4xx or 5xx) API responses. Generic `Exception` catches might hide specific API issues.
- gotcha Rate Limiting and Retries: While the SDK has built-in exponential backoff for 408, 429, and 5xx status codes, users should be aware that 429 (Too Many Requests) specifically indicates rate limits.
- gotcha Idempotent Operations: For operations that create resources (e.g., `client.inboxes.create()`), retrying without care can lead to duplicates. The `client_id` parameter helps prevent this.
- gotcha Asynchronous Client Usage: When using `AsyncAgentMail` with a custom HTTPX client, ensure you pass `httpx.AsyncClient()` and not `httpx.Client()` to the `httpx_client` parameter.
Install
-
pip install agentmail -
pip install agentmail python-dotenv
Imports
- AgentMail
from agentmail import AgentMail
- AsyncAgentMail
from agentmail import AsyncAgentMail
- ApiError
from agentmail.core.api_error import ApiError
Quickstart
import os
from agentmail import AgentMail
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env file
# Ensure AGENTMAIL_API_KEY is set in your .env file or environment variables
api_key = os.environ.get('AGENTMAIL_API_KEY', '')
if not api_key:
raise ValueError("AGENTMAIL_API_KEY environment variable not set.")
client = AgentMail(api_key=api_key)
def create_and_send_email():
try:
# Create an inbox (optional, often you'd use an existing one)
# For idempotency, you can pass a client_id:
# inbox = client.inboxes.create(username="my-agent-inbox", client_id="unique-id-123")
inbox = client.inboxes.create()
print(f"Inbox created: {inbox.inbox_id}")
# Send an email
send_response = client.inboxes.messages.send(
inbox_id=inbox.inbox_id,
to="recipient@example.com", # Replace with a real recipient email
subject="Hello from AgentMail!",
text="This is a test email sent from your AgentMail agent."
)
print(f"Email sent: Message ID {send_response.message_id}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
create_and_send_email()