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
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
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 - requiredpassword(str): Email password or app-specific password - requiredprovider(str): Provider preset ("gmail","outlook","yahoo","icloud") - auto-configures IMAP/SMTPimap_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:
| Provider | IMAP Host | SMTP Host | Notes |
|---|---|---|---|
| gmail | imap.gmail.com:993 | smtp.gmail.com:587 | Requires app-specific password |
| outlook | outlook.office365.com:993 | smtp.office365.com:587 | Enable IMAP in settings |
| yahoo | imap.mail.yahoo.com:993 | smtp.mail.yahoo.com:587 | Requires app-specific password |
| icloud | imap.mail.me.com:993 | smtp.mail.me.com:587 | Requires app-specific password |
#Connection Methods
Using provider preset (recommended):
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:
# 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
#Tool-Based Integration (Recommended)
Email plugin exposes email operations as tools that agents can use autonomously:
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:
| Tool | Description | Parameters |
|---|---|---|
| list_emails | List emails from folder | folder (string: INBOX), limit (int: 10), unread_only (bool: false) |
| read_email | Read full email content | email_id (required), folder (string: INBOX), mark_as_read (bool: false) |
| send_email | Send new email | to (required), subject (required), body (required), html (bool), cc |
| reply_to_email | Reply to existing email | email_id (required), body (required), html (bool) |
| search_emails | Search with IMAP criteria | query (required), limit (int: 10) |
Tool Categories: email
Tool Source: plugin
#Tool Usage Example
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:
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
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
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
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
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
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 senderTO "email@example.com"- Emails to specific recipientSUBJECT "keyword"- Emails with keyword in subjectBODY "keyword"- Emails with keyword in bodySINCE "01-Jan-2024"- Emails after dateBEFORE "31-Dec-2024"- Emails before dateUNSEEN- Unread emailsSEEN- Read emails
#Delete Email
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
- Enable 2-Step Verification in Google Account settings
- Generate App Password:
- Visit: https://myaccount.google.com/apppasswords
- Create app password for "Mail"
- Use the 16-character password in your code
- Enable IMAP:
- Gmail Settings → Forwarding and POP/IMAP
- Enable IMAP access
mail = email(
email_address="your.email@gmail.com",
password="xxxx xxxx xxxx xxxx", # 16-char app password
provider="gmail"
)#Outlook/Microsoft 365
- Enable IMAP in Outlook settings
- Use app password if 2FA is enabled
- Configure in code:
mail = email(
email_address="your.email@outlook.com",
password="your_password_or_app_password",
provider="outlook"
)#Yahoo Mail
- Generate App Password:
- Account Settings → Security
- Generate app password
- Use app password in code:
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
limitparameter to avoid timeouts - Use
unread_only=Trueto 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:
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 minutesCustomer Support Automation:
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:
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
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
| Issue | Solution |
|---|---|
| Authentication failed | Use app-specific password, not account password |
| Connection timeout | Check network, verify IMAP/SMTP hosts and ports |
| Gmail authentication failed | Enable 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 returned | Check folder name (use "INBOX" not "inbox"), verify search criteria |
| Cannot send email | Verify SMTP settings, check recipient email format |
| Attachments not downloading | Use read_email() not list_emails() for full content |
| "Unknown provider" error | Use: gmail, outlook, yahoo, or icloud (lowercase) |
#Next Steps
- Slack Plugin - Team messaging integration
- Redis Plugin - Pub/sub messaging and caching
- Workflows - Use email in multi-agent workflows
- Plugin Overview - Explore other plugins