Skip to main content

simple-email-gw

PyPI Python uv CI Coverage License Agentic

A simple email gateway with IMAP/SMTP clients, connection pooling, and MCP server for AI assistant integration.

Note: This package provides both async and sync APIs. Async clients are recommended for async applications. Use sync wrapper clients (SyncIMAPClient, SyncSMTPClient) for simpler synchronous code.

Rationale

This project was built using an agentic workflow — agents created the implementation from architectural requirements. For the full story, see the rationale documentation <https://simple-email-gw.readthedocs.io/en/latest/rationale.html>_.

Features

  • Async IMAP and SMTP clients (aioimaplib, aiosmtplib)
  • Sync wrapper clients for simpler synchronous usage (SyncIMAPClient, SyncSMTPClient)
  • Connection pooling with automatic management
  • Token bucket rate limiting
  • Audit logging for security compliance
  • CRLF injection prevention
  • Recipient whitelist enforcement
  • TLS 1.2+ minimum encryption
  • MCP server for AI assistant integration

Installation

Using pip

pip install simple-email-gw

Using uv

uv add simple-email-gw

Quick Start

MCP Server

Run the MCP server for AI assistant integration:

# Set environment variables
export EMAIL_IMAP_HOST=imap.gmail.com
export EMAIL_SMTP_HOST=smtp.gmail.com
export EMAIL_USERNAME=your-email@gmail.com
export EMAIL_PASSWORD=your-app-password

# Run server
uvx --from simple-email-gw email-gw-mcp-server

Programmatic Usage

import asyncio
from simple_email_gw import IMAPClient, SMTPClient, EmailAccount

# Create account configuration
account = EmailAccount(
  name="work",
  imap_host="imap.gmail.com",
  smtp_host="smtp.gmail.com",
  username="user@gmail.com",
  password="app-password"
)

async def main():
  # Use IMAP client
  async with IMAPClient(account) as client:
    folders = await client.list_folders()
    messages = await client.search(folder="INBOX")
    print(f"Found {len(messages)} messages")

  # Use SMTP client
  smtp = SMTPClient(account)
  result = await smtp.send_email(
    to=["recipient@example.com"],
    subject="Test",
    body="Hello world"
  )
  print(f"Sent: {result}")

asyncio.run(main())

Sync Client Usage

For simpler synchronous code, use the sync wrapper clients:

from simple_email_gw import SyncIMAPClient, SyncSMTPClient, EmailAccount

# Create account configuration
account = EmailAccount(
  name="work",
  imap_host="imap.gmail.com",
  smtp_host="smtp.gmail.com",
  username="user@gmail.com",
  password="app-password"
)

# Sync IMAP usage
with SyncIMAPClient(account) as client:
  folders = client.list_folders()
  messages = client.search(folder="INBOX")
  print(f"Found {len(messages)} messages")

# Sync SMTP usage
with SyncSMTPClient(account) as client:
  result = client.send_email(
    to=["recipient@example.com"],
    subject="Test",
    body="Hello world"
  )
  print(f"Sent: {result}")

Interactive CLI

Run the interactive CLI for managing email:

# Create .env file with your email account
cp .env.example .env
# Edit .env with your account details

# Run CLI
uv run email-gw-cli

# Or if installed globally
email-gw-cli

Getting Started:

none:INBOX> help                    # Show available commands
none:INBOX> accounts                # List configured accounts
none:INBOX> use work                # Connect to 'work' account
work:INBOX> folders                 # List folders
work:INBOX> ls                      # List emails
work:INBOX> show 42                 # View email #42
work:INBOX> write --sent alice@example.com   # Compose and save copy to Sent
work:INBOX> reply --sent 42         # Reply and save copy to Sent
work:INBOX> write --sent --sent-folder "Sent Items" alice@example.com  # Custom Sent folder
work:INBOX> theme                   # Toggle light/dark theme
work:INBOX> quit                    # Exit CLI

The --sent flag (also --save-sent) enables opt-in auto-append to the IMAP Sent folder after a successful send. It triggers a Save a copy to Sent folder? (y/n) prompt and can be combined with --sent-folder to override the destination folder.

Features:

  • Command history - Use ↑/↓ arrows to navigate previous commands
  • Theme support - Switch between light and dark color themes
  • Auto-completion - Tab completion for commands (coming soon)
  • Rich formatting - Tables, panels, and syntax-highlighted output

See the CLI documentation for complete command reference.

Note: Sync clients use a dedicated event loop in a background thread (Strategy 2). They preserve all async client benefits including connection pooling, rate limiting, and security features. Use async clients in async contexts (FastAPI, asyncio, etc.) for better performance.

Configuration

Environment Variables

The CLI and MCP server automatically load environment variables from a .env file in the current directory. Copy .env.example to .env and configure your email accounts:

cp .env.example .env
# Edit .env with your email account details

Single account configuration:

EMAIL_IMAP_HOST=imap.gmail.com
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_USERNAME=user@gmail.com
EMAIL_PASSWORD=app-password

Multiple accounts (JSON):

EMAIL_ACCOUNTS_JSON='[{"name":"work","imap_host":"imap.gmail.com","smtp_host":"smtp.gmail.com","username":"work@example.com","password":"secret"},{"name":"personal","imap_host":"imap.icloud.com","smtp_host":"smtp.icloud.com","username":"personal@icloud.com","password":"secret"}]'

See the configuration documentation <https://simple-email-gw.readthedocs.io/en/latest/configuration.html>_ for detailed options.

Rate Limiting

Default limits:

  • IMAP: 60 requests per minute per account
  • SMTP: 100 sends per hour per account

Recipient Whitelist

Restrict outgoing emails to specific domains or addresses:

EMAIL_RECIPIENT_WHITELIST_DOMAINS=gmail.com,icloud.com
EMAIL_RECIPIENT_WHITELIST_ADDRESSES=admin@company.com

Security Features

TLS 1.2+ Minimum

All connections require TLS 1.2 or higher. Connections with older TLS versions are rejected.

CRLF Injection Prevention

All email headers are sanitized to prevent CRLF injection attacks:

  • Subject lines
  • Message-IDs
  • References headers
  • Email addresses

Recipient Whitelist

Optional whitelist restricts outgoing emails to approved recipients.

Rate Limiting

Token bucket algorithm prevents abuse with separate limits per account.

Audit Logging

All operations are logged for security compliance.

See the security documentation <https://simple-email-gw.readthedocs.io/en/latest/security.html>_ for complete details.

MCP Tools

Tool Purpose
list_accounts List configured email accounts
list_folders List IMAP folders
search_emails Search messages by criteria
get_email Fetch single message
download_attachment Download attachment to workspace
send_email Send new email (optional auto-save to Sent)
reply_email Reply to thread (optional auto-save to Sent)
move_email Move between folders
delete_email Delete message
mark_email_read Mark message as read
append_email Append a raw RFC822 message to an IMAP folder

Auto-Save Sent Folder

send_email and reply_email support optional auto-append to the account's Sent folder:

  • append_to_sent: bool - Append a copy after a successful SMTP send (default: False).
  • append_folder: str | None - Override the destination folder (default: auto-detected Sent folder).

The Sent folder is detected using the IMAP \Sent special-use flag when available, with a deterministic fallback to Sent, Sent Items, and Sent Messages. If auto-append fails, the send still succeeds and a warning is returned.

Append Email Tool

append_email performs a pure IMAP APPEND of a base64-encoded RFC822 message. The message is re-parsed, threading headers are sanitized, and flags are restricted to the allowlist \Seen, \Draft, \Answered, \Flagged.

See the API documentation <https://simple-email-gw.readthedocs.io/en/latest/api.html>_ for complete API reference.

Development

See the development documentation <https://simple-email-gw.readthedocs.io/en/latest/development.html>_ for development setup and contribution guidelines.

Quick commands:

make dev-env    # Install development dependencies
make test       # Run tests
make lint       # Run linter
make typecheck  # Run type checker
make all        # Run all checks
make email-gw-mcp-server # Run the MCP server

License

MIT License - see LICENSE for details.

Download files

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

Source Distribution

simple_email_gw-0.3.1.tar.gz (796.3 kB view details)

Uploaded Source

Built Distribution

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

simple_email_gw-0.3.1-py3-none-any.whl (54.5 kB view details)

Uploaded Python 3

File details

Details for the file simple_email_gw-0.3.1.tar.gz.

File metadata

  • Download URL: simple_email_gw-0.3.1.tar.gz
  • Upload date:
  • Size: 796.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for simple_email_gw-0.3.1.tar.gz
Algorithm Hash digest
SHA256 48d64b7baa19818f7c0ce8283cf6d641764312998e66b200ea0aadfb9a73ade1
MD5 7888e06afa96fbe09d56b2f65e02c750
BLAKE2b-256 1133b4047224e6224d49f7cef46e0f2a80b706ef4d58efc90dceb1796e534f06

See more details on using hashes here.

File details

Details for the file simple_email_gw-0.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_email_gw-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 adab433a51d88d051b506a0ac731a71b1cb45601521b95ea15be06710b804336
MD5 3c74199aaf5fb62746a709be2cfc46d9
BLAKE2b-256 f3bd1f0d7921648e51121eb6a14b0685958a66b47857fb4a6e93cee52e80c7f4

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.3.1 This release

2 files

0.3.0

2 files

0.2.1

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page