Skip to main content

Email interface for AI agents

Project description

📧 PyMailAI

Documentation Status

PyMailAI is a Python package that enables AI agents to use email as an input/output interface. It provides simple wrappers to:

  1. Get prompts from incoming emails
  2. Process them with your LLM of choice
  3. Send the responses back via email

Installation

pip install pymailai

Quick Start

Basic OpenAI Example

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...")

Anthropic Computer-Use Agent

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:

  1. First, install the required dependencies:
pip install "pymailai[anthropic]"
  1. 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"
  1. 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:

  1. Send an email to your configured email address
  2. The agent will process your request using Anthropic's computer-use capabilities
  3. Results will be sent back as email replies
  4. The agent maintains conversation context between emails

Using with Any LLM Code

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]
    )

Configuration

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

# Your LLM API keys
export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"
# ... other API keys as needed

Documentation

Full documentation is available at https://tomatyss.github.io/PyMailAI/

More Examples

Check the examples/ directory for more examples:

  • openai_completion.py: Basic OpenAI integration
  • anthropic_computer_agent.py: Anthropic computer-use agent
  • simple_ai_agent.py: Template for custom agents

Contributing

Development Setup

  1. Install development dependencies:
make install

This will install all dev dependencies and set up pre-commit hooks.

Code Quality

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

Building Documentation

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

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pymailai-0.1.1.tar.gz (23.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pymailai-0.1.1-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file pymailai-0.1.1.tar.gz.

File metadata

  • Download URL: pymailai-0.1.1.tar.gz
  • Upload date:
  • Size: 23.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for pymailai-0.1.1.tar.gz
Algorithm Hash digest
SHA256 1e9b01e7b73ad0bb66c5436457a1b058d5aa65d4901ab55d14fb4ae6d85822c9
MD5 0f38e4736c15ab8fd8162d95a220f641
BLAKE2b-256 13105d91867d24669ea82221432d8ad3dd11b5ad202c891e267bd305b3d8d7b4

See more details on using hashes here.

File details

Details for the file pymailai-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: pymailai-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for pymailai-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e3a9efdb8cb3e740fb5cb15fff9a96c8df1557701ad13fbd30e8ad69f6064654
MD5 f6db490e9ebcab893b5701b7619ea588
BLAKE2b-256 6335d83591fb8d26b0493dc0eea84c7a09fccea95b74bb1bd65accd119a90ea3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page