Email Agent
The EmailAgent class is the main component of pymailai that handles email processing and AI-powered responses.
- class pymailai.agent.EmailAgent(config_or_client, message_handler=None)[source]
Bases:
object
Process incoming emails and generate responses using AI.
The EmailAgent can work with either an EmailConfig for IMAP/SMTP or a BaseEmailClient for custom implementations:
Example with EmailConfig:
from pymailai import EmailAgent, EmailConfig # Configure IMAP/SMTP config = EmailConfig( imap_server="imap.gmail.com", smtp_server="smtp.gmail.com", email="your-email@gmail.com", password="your-password" ) # Create agent with config agent = EmailAgent(config, message_handler=handler)
Example with Gmail API:
from pymailai import EmailAgent from pymailai.gmail import ServiceAccountCredentials from pymailai.gmail_client import GmailClient # Set up service account creds = ServiceAccountCredentials( credentials_path="credentials.json", delegated_email="user@yourdomain.com", scopes=["https://www.googleapis.com/auth/gmail.modify"] ) # Create Gmail client client = GmailClient(creds.get_gmail_service()) # Create agent with client agent = EmailAgent(client, message_handler=handler)
Example with custom client:
from pymailai import EmailAgent from pymailai.base_client import BaseEmailClient class MyCustomClient(BaseEmailClient): async def connect(self) -> None: # Connect to service pass async def disconnect(self) -> None: # Disconnect from service pass async def fetch_new_messages(self) -> AsyncGenerator[EmailData, None]: # Fetch new messages pass async def send_message(self, message: EmailData) -> None: # Send a message pass async def mark_as_read(self, message_id: str) -> None: # Mark message as read pass # Create agent with custom client agent = EmailAgent(MyCustomClient(), message_handler=handler)
- Parameters:
config_or_client (EmailConfig | BaseEmailClient)
message_handler (Callable[[EmailData], Coroutine[Any, Any, EmailData | None]] | None)
- __init__(config_or_client, message_handler=None)[source]
Initialize the email agent.
- Parameters:
config_or_client (EmailConfig | BaseEmailClient) – Either EmailConfig for IMAP/SMTP or a BaseEmailClient instance
message_handler (Callable[[EmailData], Coroutine[Any, Any, EmailData | None]] | None) – Optional async callback for custom message processing
- async process_message(message)[source]
Process an incoming email message.
This method can be overridden to implement custom processing logic. By default, it calls the message_handler if one was provided.
Type Definitions
- pymailai.agent.MessageHandler: Callable[[EmailData], Coroutine[Any, Any, EmailData | None]]
Type alias for message handler functions that process incoming emails.
The handler should be an async function that takes an
EmailData
object and returns an optional responseEmailData
.Example handler:
async def echo_handler(message: EmailData) -> Optional[EmailData]: """Echo back any received email.""" return EmailData( message_id="", # Will be generated by email service subject=f"Re: {message.subject}", from_address="", # Will be set by email service to_addresses=[message.from_address], cc_addresses=[], body_text=f"Received: {message.body_text}", body_html=f"<p>Received:</p><blockquote>{message.body_html}</blockquote>", timestamp=datetime.now(), in_reply_to=message.message_id )
Client Architecture
The EmailAgent supports different email clients through a common interface:
BaseEmailClient - Abstract base class defining the email client interface - Methods for connecting, sending, receiving, and managing emails - Used by all concrete client implementations
EmailClient - Standard IMAP/SMTP implementation - Works with any email service supporting these protocols - Configured through EmailConfig
GmailClient - Direct Gmail API implementation - Supports service account authentication - Better performance and reliability for Gmail
Custom Clients - Implement BaseEmailClient for custom email services - Full control over email operations - Can integrate with any email API or protocol