PyMailAI is a Python package that enables AI agents to use email as an input/output interface. It provides simple wrappers to:
- Get prompts from incoming emails
- Process them with your LLM of choice
- Send the responses back via email
pip install pymailai
Here's how to use PyMailAI with OpenAI's API to create an email-based AI assistant:
import os
import asyncio
import openai
from pymailai import EmailAgent, EmailConfig
from pymailai.message import EmailData
# Configure OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
async def process_with_openai(message: EmailData):
"""Process email content using OpenAI."""
try:
# Send email content to OpenAI
completion = await openai.ChatCompletion.acreate(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": message.body_text}
]
)
# Get AI response
ai_response = completion.choices[0].message.content
# Send response back via email
return EmailData(
message_id="", # Will be generated by email server
subject=f"Re: {message.subject}",
from_address=message.to_addresses[0],
to_addresses=[message.from_address],
cc_addresses=[],
body_text=ai_response,
body_html=None,
timestamp=message.timestamp,
in_reply_to=message.message_id,
references=[message.message_id]
)
except Exception as e:
print(f"Error: {e}")
return None
# Configure email settings
config = EmailConfig(
imap_server="imap.gmail.com",
smtp_server="smtp.gmail.com",
email=os.getenv("EMAIL_ADDRESS"),
password=os.getenv("EMAIL_PASSWORD")
)
# Create and run the agent
async with EmailAgent(config, message_handler=process_with_openai) as agent:
print(f"AI Email Agent started. Monitoring {config.email}")
try:
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
print("Stopping...")
PyMailAI can be used with Anthropic's computer-use agent to create an email interface for interacting with the computer. Here's how to set it up:
- First, install the required dependencies:
pip install "pymailai[anthropic]"
- Set up your environment variables:
# Email settings
export EMAIL_ADDRESS="your-email@gmail.com"
export EMAIL_PASSWORD="your-app-password"
export EMAIL_IMAP_SERVER="imap.gmail.com"
export EMAIL_SMTP_SERVER="smtp.gmail.com"
# Anthropic API key
export ANTHROPIC_API_KEY="your-anthropic-key"
- Run the computer-use agent example:
python examples/anthropic_computer_agent.py
This will start an email agent that:
- Monitors your inbox for new emails
- Processes them using Anthropic's computer-use agent
- Sends back the results via email
- Supports all computer-use capabilities (bash commands, file editing, etc.)
Example usage:
- Send an email to your configured email address
- The agent will process your request using Anthropic's computer-use capabilities
- Results will be sent back as email replies
- The agent maintains conversation context between emails
PyMailAI can wrap any existing LLM code. Just use the email body as your prompt:
async def your_llm_handler(message: EmailData):
"""Use any LLM code here."""
# Get prompt from email
prompt = message.body_text
# Process with your LLM code
response = your_llm_function(prompt) # Your existing LLM code
# Send result back via email
return EmailData(
message_id="",
subject=f"Re: {message.subject}",
from_address=message.to_addresses[0],
to_addresses=[message.from_address],
cc_addresses=[],
body_text=response,
body_html=None,
timestamp=message.timestamp,
in_reply_to=message.message_id,
references=[message.message_id]
)
The package uses environment variables for configuration:
# Email settings
export EMAIL_ADDRESS="your-email@gmail.com"
export EMAIL_PASSWORD="your-app-password"
export EMAIL_IMAP_SERVER="imap.gmail.com" # Optional, default: imap.gmail.com
export EMAIL_SMTP_SERVER="smtp.gmail.com" # Optional, default: smtp.gmail.com
export EMAIL_IMAP_PORT="993" # Optional, default: 993
export EMAIL_SMTP_PORT="465" # Optional, default: 465 (SSL/TLS) or 587 (STARTTLS)
export EMAIL_CHECK_INTERVAL="60" # Optional, seconds between inbox checks, default: 60
# Your LLM API keys
export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"
# ... other API keys as needed
PyMailAI includes robust connection handling features to maintain reliable email communication:
-
Automatic Reconnection: The client automatically detects disconnections and reconnects when:
- SMTP server connection is lost
- Connection timeouts occur
- Network interruptions happen
-
Retry Logic: Built-in retry mechanisms with exponential backoff for:
- Sending messages (max 3 retries)
- Marking messages as read (max 3 retries)
- Connection attempts
-
Error Recovery: The agent gracefully handles various error scenarios:
- Connection drops
- Server timeouts
- Network issues
- Message processing failures
Example with custom retry settings:
from pymailai import EmailAgent, EmailConfig, EmailData
# Configure email with custom settings
config = EmailConfig(
email=os.getenv("EMAIL_ADDRESS"),
password=os.getenv("EMAIL_PASSWORD"),
check_interval=30, # Check inbox every 30 seconds
timeout=30, # Connection timeout in seconds
)
async def process_message(message: EmailData):
# Your message processing logic here
response = ...
# Send with custom retry settings
await agent._client.send_message(response, max_retries=5) # Increase retries for important messages
For long-running applications, the agent automatically:
- Maintains SMTP connection health
- Recovers from disconnections
- Implements backoff strategies to prevent server stress
- Logs connection events for monitoring
Full documentation is available at https://tomatyss.github.io/PyMailAI/
Check the examples/
directory for more examples:
openai_completion.py
: Basic OpenAI integrationanthropic_computer_agent.py
: Anthropic computer-use agentollama_completion.py
: Local LLM integration with Ollamasimple_ai_agent.py
: Template for custom agents
To use PyMailAI with Ollama's local LLM models:
- Install the required dependencies:
pip install "pymailai[ollama]"
- Install and start Ollama from https://ollama.ai, then pull the model:
ollama pull llama3.2
- Set up your environment variables:
export EMAIL_ADDRESS="your-email@example.com"
export EMAIL_PASSWORD="your-email-password"
export EMAIL_IMAP_SERVER="your-imap-server"
export EMAIL_SMTP_SERVER="your-smtp-server"
export EMAIL_IMAP_PORT="993"
export EMAIL_SMTP_PORT="465"
- Run the Ollama example:
python examples/ollama_completion.py
- Install development dependencies:
make install
This will install all dev dependencies and set up pre-commit hooks.
We use pre-commit hooks to ensure code quality. The hooks run automatically on commit and include:
- black (code formatting)
- isort (import sorting)
- flake8 (linting)
- mypy (type checking)
To manually install the pre-commit hooks:
make install-hooks
To build the documentation locally:
# Install Sphinx and theme
pip install sphinx sphinx-rtd-theme
# Build the docs
cd docs
make html
# View the docs (macOS)
open build/html/index.html
MIT License