Email Plugin

Universal email integration with IMAP/SMTP protocols supporting Gmail, Outlook, Yahoo, and any standard email provider.

#Installation

No additional packages required - uses Python's standard library (imaplib, smtplib, email).

#Quick Start

python
from daita import Agent
from daita.plugins import email
 
# Create plugin using provider preset
mail = email(
    email_address="your.email@gmail.com",
    password="app_password",
    provider="gmail"
)
 
# Agent uses email tools autonomously
agent = Agent(
    name="Email Assistant",
    prompt="You are an email assistant. Help users manage their inbox.",
    tools=[mail]
)
 
await agent.start()
result = await agent.run("Check my unread emails and summarize them")
await agent.stop()

#Direct Usage

The plugin can be used directly without agents for programmatic email management. However, the main value is agent integration - enabling LLMs to autonomously read, search, and send emails based on natural language instructions.

#Connection Parameters

python
email(
    email_address: str,
    password: str,
    provider: Optional[str] = None,
    imap_host: Optional[str] = None,
    imap_port: int = 993,
    smtp_host: Optional[str] = None,
    smtp_port: int = 587,
    use_tls: bool = True
)

#Parameters

  • email_address (str): Your email address - required
  • password (str): Email password or app-specific password - required
  • provider (str): Provider preset ("gmail", "outlook", "yahoo", "icloud") - auto-configures IMAP/SMTP
  • imap_host (str): IMAP server host (overrides provider preset)
  • imap_port (int): IMAP server port (default: 993)
  • smtp_host (str): SMTP server host (overrides provider preset)
  • smtp_port (int): SMTP server port (default: 587)
  • use_tls (bool): Use TLS for SMTP connection (default: True)

#Provider Presets

Supported providers with automatic configuration:

ProviderIMAP HostSMTP HostNotes
gmailimap.gmail.com:993smtp.gmail.com:587Requires app-specific password
outlookoutlook.office365.com:993smtp.office365.com:587Enable IMAP in settings
yahooimap.mail.yahoo.com:993smtp.mail.yahoo.com:587Requires app-specific password
icloudimap.mail.me.com:993smtp.mail.me.com:587Requires app-specific password

#Connection Methods

Using provider preset (recommended):

python
from daita.plugins import email
import os
 
# Gmail
async with email(
    email_address="user@gmail.com",
    password=os.getenv("GMAIL_APP_PASSWORD"),
    provider="gmail"
) as mail:
    emails = await mail.list_emails(unread_only=True)
 
# Outlook
async with email(
    email_address="user@company.com",
    password=os.getenv("OUTLOOK_PASSWORD"),
    provider="outlook"
) as mail:
    emails = await mail.list_emails()

Custom IMAP/SMTP configuration:

python
# Custom email server
async with email(
    email_address="user@company.com",
    password="password",
    imap_host="mail.company.com",
    smtp_host="mail.company.com"
) as mail:
    emails = await mail.list_emails()

#Using with Agents

Email plugin exposes email operations as tools that agents can use autonomously:

python
from daita import Agent
from daita.plugins import email
import os
 
# Create email plugin
mail = email(
    email_address=os.getenv("EMAIL_ADDRESS"),
    password=os.getenv("EMAIL_PASSWORD"),
    provider="gmail"
)
 
# Pass plugin to agent - agent can now use email tools autonomously
agent = Agent(
    name="Email Assistant",
    prompt="""You are an email assistant. Help users manage their inbox:
    - Read and summarize unread emails
    - Search for specific emails
    - Send replies and new emails
    - Organize and prioritize messages""",
    llm_provider="openai",
    model="gpt-4",
    tools=[mail]
)
 
await agent.start()
 
# Agent autonomously uses email tools to answer questions
result = await agent.run("Check my unread emails from my boss and summarize the important ones")
 
# The agent will autonomously:
# 1. Use list_emails to find unread messages
# 2. Use read_email to read full content
# 3. Analyze and summarize important emails
 
await agent.stop()

#Available Tools

The Email plugin exposes these tools to LLM agents:

ToolDescriptionParameters
list_emailsList emails from folderfolder (string: INBOX), limit (int: 10), unread_only (bool: false)
read_emailRead full email contentemail_id (required), folder (string: INBOX), mark_as_read (bool: false)
send_emailSend new emailto (required), subject (required), body (required), html (bool), cc
reply_to_emailReply to existing emailemail_id (required), body (required), html (bool)
search_emailsSearch with IMAP criteriaquery (required), limit (int: 10)

Tool Categories: email Tool Source: plugin

#Tool Usage Example

python
from daita import Agent
from daita.plugins import email
 
# Setup email with tool integration
mail = email(
    email_address="assistant@company.com",
    password="app_password",
    provider="gmail"
)
 
agent = Agent(
    name="Customer Support Agent",
    prompt="You are a customer support agent. Help manage customer emails.",
    llm_provider="openai",
    model="gpt-4",
    tools=[mail]
)
 
await agent.start()
 
# Natural language command - agent uses tools autonomously
result = await agent.run("""
Check my inbox:
1. Find emails from customers asking about pricing
2. Read the most recent one
3. Send a helpful reply with our pricing information
""")
 
# Agent orchestrates email tool calls to complete the task
print(result)
await agent.stop()

#Direct Email Operations (Scripts)

For scripts that need email without agent capabilities:

python
from daita.plugins import email
import os
 
async with email(
    email_address=os.getenv("EMAIL_ADDRESS"),
    password=os.getenv("EMAIL_PASSWORD"),
    provider="gmail"
) as mail:
    # List unread emails
    unread = await mail.list_emails(unread_only=True, limit=5)
    print(f"Found {len(unread)} unread emails")
 
    # Read first email
    if unread:
        email_data = await mail.read_email(unread[0]['id'])
        print(f"Subject: {email_data['subject']}")
        print(f"From: {email_data['from']}")
        print(f"Body: {email_data['body']}")
 
    # Send new email
    result = await mail.send_email(
        to="recipient@example.com",
        subject="Automated Report",
        body="Here is your daily report."
    )
    print(f"Email sent: {result['success']}")

#Email Operations

#List Emails

python
from daita.plugins import email
 
async with email(email_address="user@gmail.com", password="pass", provider="gmail") as mail:
    # List all emails (latest 10)
    emails = await mail.list_emails()
 
    # List unread only
    unread = await mail.list_emails(unread_only=True, limit=20)
 
    # List from specific folder
    sent = await mail.list_emails(folder="SENT", limit=5)
 
    # Custom search criteria
    important = await mail.list_emails(
        search_criteria='FROM "boss@company.com"'
    )

#Read Email

python
from daita.plugins import email
 
async with email(email_address="user@gmail.com", password="pass", provider="gmail") as mail:
    # Get email list
    emails = await mail.list_emails(limit=1)
    email_id = emails[0]['id']
 
    # Read email (don't mark as read)
    email_data = await mail.read_email(email_id)
 
    # Access content
    print(f"Subject: {email_data['subject']}")
    print(f"From: {email_data['from']}")
    print(f"Body: {email_data['body']}")
    print(f"Attachments: {len(email_data['attachments'])}")
 
    # Read and mark as read
    email_data = await mail.read_email(email_id, mark_as_read=True)

#Send Email

python
from daita.plugins import email
 
async with email(email_address="user@gmail.com", password="pass", provider="gmail") as mail:
    # Simple text email
    result = await mail.send_email(
        to="recipient@example.com",
        subject="Meeting Tomorrow",
        body="Don't forget our meeting at 10am tomorrow."
    )
 
    # HTML email with CC
    result = await mail.send_email(
        to="team@company.com",
        cc="manager@company.com",
        subject="Weekly Update",
        body="<h1>Weekly Update</h1><p>Great progress this week!</p>",
        html=True
    )
 
    # Email with attachments
    result = await mail.send_email(
        to="client@example.com",
        subject="Project Report",
        body="Please find the attached report.",
        attachments=["/path/to/report.pdf", "/path/to/data.xlsx"]
    )
 
    # Multiple recipients
    result = await mail.send_email(
        to=["user1@example.com", "user2@example.com"],
        cc=["manager@company.com"],
        bcc=["archive@company.com"],
        subject="Team Announcement",
        body="Important team update..."
    )

#Reply to Email

python
from daita.plugins import email
 
async with email(email_address="user@gmail.com", password="pass", provider="gmail") as mail:
    # Get email to reply to
    emails = await mail.list_emails(unread_only=True, limit=1)
    email_id = emails[0]['id']
 
    # Send reply (automatically sets To: and Subject:)
    result = await mail.reply_to_email(
        email_id=email_id,
        body="Thank you for your email. I'll look into this and get back to you soon."
    )
 
    # Reply with HTML formatting
    result = await mail.reply_to_email(
        email_id=email_id,
        body="<p>Thank you!</p><p>Best regards,<br>Support Team</p>",
        html=True
    )

#Search Emails

python
from daita.plugins import email
 
async with email(email_address="user@gmail.com", password="pass", provider="gmail") as mail:
    # Search by sender
    emails = await mail.search_emails('FROM "boss@company.com"')
 
    # Search by subject
    emails = await mail.search_emails('SUBJECT "invoice"')
 
    # Search by date
    emails = await mail.search_emails('SINCE "01-Jan-2024"')
 
    # Complex search (combine criteria)
    emails = await mail.search_emails('FROM "client" SUBJECT "urgent"')

Common IMAP Search Criteria:

  • FROM "email@example.com" - Emails from specific sender
  • TO "email@example.com" - Emails to specific recipient
  • SUBJECT "keyword" - Emails with keyword in subject
  • BODY "keyword" - Emails with keyword in body
  • SINCE "01-Jan-2024" - Emails after date
  • BEFORE "31-Dec-2024" - Emails before date
  • UNSEEN - Unread emails
  • SEEN - Read emails

#Delete Email

python
from daita.plugins import email
 
async with email(email_address="user@gmail.com", password="pass", provider="gmail") as mail:
    # Mark for deletion (move to trash)
    result = await mail.delete_email(email_id="12345")
 
    # Permanently delete
    result = await mail.delete_email(email_id="12345", permanent=True)

#Authentication Setup

#Gmail

  1. Enable 2-Step Verification in Google Account settings
  2. Generate App Password:
  3. Enable IMAP:
    • Gmail Settings → Forwarding and POP/IMAP
    • Enable IMAP access
python
mail = email(
    email_address="your.email@gmail.com",
    password="xxxx xxxx xxxx xxxx",  # 16-char app password
    provider="gmail"
)

#Outlook/Microsoft 365

  1. Enable IMAP in Outlook settings
  2. Use app password if 2FA is enabled
  3. Configure in code:
python
mail = email(
    email_address="your.email@outlook.com",
    password="your_password_or_app_password",
    provider="outlook"
)

#Yahoo Mail

  1. Generate App Password:
    • Account Settings → Security
    • Generate app password
  2. Use app password in code:
python
mail = email(
    email_address="your.email@yahoo.com",
    password="app_password",
    provider="yahoo"
)

#Best Practices

Security:

  • Store credentials in environment variables, never hardcode
  • Use app-specific passwords instead of account passwords
  • Enable 2-factor authentication on email accounts
  • Use separate email accounts for automation (not your personal account)

Performance:

  • Limit email fetches with limit parameter to avoid timeouts
  • Use unread_only=True to reduce processing
  • Search with specific criteria to narrow results
  • Close connections properly using context managers (async with)

Error Handling:

  • Handle authentication errors gracefully
  • Check for network connectivity issues
  • Validate email addresses before sending
  • Use try-except blocks for production code

Email Management:

  • Mark emails as read after processing to avoid duplicates
  • Use folders to organize emails (INBOX, SENT, Archives)
  • Delete or archive processed emails to keep inbox clean
  • Use search instead of listing all emails for better performance

#Common Patterns

Automated Email Monitoring:

python
from daita import Agent
from daita.plugins import email
import asyncio
 
# Monitor inbox every 5 minutes
mail = email(email_address="monitor@company.com", password="pass", provider="gmail")
 
agent = Agent(
    name="Email Monitor",
    prompt="Monitor inbox for urgent emails and alert on important messages.",
    tools=[mail]
)
 
await agent.start()
 
while True:
    result = await agent.run("Check for unread emails marked urgent and summarize them")
    print(result)
    await asyncio.sleep(300)  # 5 minutes

Customer Support Automation:

python
from daita import Agent
from daita.plugins import email
 
mail = email(email_address="support@company.com", password="pass", provider="gmail")
 
agent = Agent(
    name="Support Agent",
    prompt="""You are a customer support agent.
    Read customer emails, categorize them, and send appropriate responses.
    For billing questions, provide pricing info.
    For technical issues, acknowledge and create a ticket.""",
    tools=[mail]
)
 
await agent.start()
 
result = await agent.run("""
Process my inbox:
1. Read unread customer emails
2. Categorize by type (billing, technical, general)
3. Send appropriate responses
4. Mark as read after handling
""")

Email Digest Generator:

python
from daita import Agent
from daita.plugins import email
 
mail = email(email_address="user@company.com", password="pass", provider="gmail")
 
agent = Agent(
    name="Digest Generator",
    prompt="Generate daily email digests summarizing important emails.",
    tools=[mail]
)
 
await agent.start()
 
result = await agent.run("""
Create a daily digest:
1. Find emails received today
2. Summarize key points from each
3. Group by sender or topic
4. Send digest to my personal email
""")

#Error Handling

python
from daita.plugins import email
 
try:
    async with email(
        email_address="user@gmail.com",
        password="app_password",
        provider="gmail"
    ) as mail:
        emails = await mail.list_emails(unread_only=True)
 
        for email_data in emails:
            content = await mail.read_email(email_data['id'])
            print(f"Read: {content['subject']}")
 
except ValueError as e:
    if "email_address cannot be empty" in str(e):
        print("Error: Email address is required")
    elif "Unknown provider" in str(e):
        print("Error: Invalid provider name")
    else:
        print(f"Configuration error: {e}")
 
except RuntimeError as e:
    if "authentication failed" in str(e).lower():
        print("Error: Check credentials or use app-specific password")
    elif "connection" in str(e).lower():
        print("Error: Cannot connect to email server")
    else:
        print(f"Email operation error: {e}")

#Troubleshooting

IssueSolution
Authentication failedUse app-specific password, not account password
Connection timeoutCheck network, verify IMAP/SMTP hosts and ports
Gmail authentication failedEnable 2FA and generate app password at myaccount.google.com
Outlook "Access denied"Enable IMAP in Outlook settings, use app password if 2FA enabled
No emails returnedCheck folder name (use "INBOX" not "inbox"), verify search criteria
Cannot send emailVerify SMTP settings, check recipient email format
Attachments not downloadingUse read_email() not list_emails() for full content
"Unknown provider" errorUse: gmail, outlook, yahoo, or icloud (lowercase)

#Next Steps