Skip to main content
Glama
cat-people-82

Email MCP Server

Email MCP Server

IMAPおよびSMTP経由でメールアクセスを提供するModel Context Protocol (MCP)サーバーです。AIエージェントやアプリケーションが、標準化されたHTTP/SSEインターフェースを通じてメールの読み取り、検索、送信、管理を行えるようにします。

機能

  • 9つのメールツール (MCP経由):

    • list_folders - すべてのIMAPメールボックス/フォルダーを一覧表示

    • search_emails - フィルター(送信者、件名、日付範囲、既読/フラグ状態)を使用してメールを検索

    • read_email - 本文や添付ファイルのメタデータを含むメールの全内容を取得

    • mark_email - メールを既読/未読、またはフラグ付き/フラグなしに設定

    • move_email - フォルダー間でメールを移動

    • send_email - 新規メールを送信(プレーンテキストまたはマルチパートHTML)

    • reply_email - スレッドヘッダーを保持したままメールに返信

    • download_attachment - メール添付ファイルをワークスペースディレクトリにダウンロード

    • send_email_with_attachments - ワークスペース内のファイルを添付してメールを送信

  • 本番環境対応のアーキテクチャ:

    • コネクションプーリングを備えた非同期ネイティブのIMAP/SMTP

    • Pydanticベースの設定とバリデーション

    • 構造化された例外による包括的なエラーハンドリング

    • X-API-KeyヘッダーによるAPIキー認証

    • Ubuntuデプロイ用のsystemdサービスファイル

  • テスト駆動開発:

    • 85以上のユニットテストおよび統合テスト

    • コア機能の100%カバレッジ

    • 再現可能なテストのためのモックメールサーバー

Claude Desktopへのインストール(推奨)

このサーバーを使用する最も簡単な方法は、Claude Desktop用の単一ファイルインストールであるMCPBバンドルを使用することです。

1. ダウンロード

最新リリースから email_mcp.mcpb をダウンロードします。

2. インストール

email_mcp.mcpb をダブルクリックします。Claude Desktopがインストールダイアログを開きます。

3. 設定

プロンプトが表示されたら、メールサーバーの認証情報を入力します。すべての値はOSのキーチェーン(macOS Keychain / Linux Secret Service)に保存されます:

フィールド

説明

例

IMAP Host

IMAPサーバーのホスト名

imap.gmail.com

IMAP Port

IMAPサーバーのポート

993 (SSL) · 143 (STARTTLS)

IMAP Username

メールアドレス

you@example.com

IMAP Password

パスワードまたはアプリパスワード

xxxx xxxx xxxx xxxx

IMAP SSL

IMAPにSSL/TLSを使用

true (ポート 993) · false (ポート 143)

SMTP Host

SMTPサーバーのホスト名

smtp.gmail.com

SMTP Port

SMTPサーバーのポート

587 (STARTTLS) · 465 (SSL)

SMTP Username

メールアドレス

you@example.com

SMTP Password

パスワードまたはアプリパスワード

xxxx xxxx xxxx xxxx

SMTP STARTTLS

STARTTLSモード

true (ポート 587) · false · none (自動)

Gmailユーザー: 通常のGoogleアカウントパスワードではなく、アプリパスワードを使用する必要があります。Gmail設定 → メール転送とPOP/IMAPでIMAPを有効にしてください。

4. 使用方法

インストールが完了すると、Claudeがメールにアクセスできるようになります。以下を試してみてください:

"今週の未読メールをリストアップして" "alice@example.comから届いたプロジェクトに関するメールを検索して" "件名を'Hello'、本文を'Hi Bob!'としてbob@example.comにメールを送って" "メールUID 12345の最初の添付ファイルをダウンロードして" "report.pdfを添付してteam@example.comにメールを送って"


要件

  • Python 3.10+ (3.13推奨)

  • IMAPおよびSMTPサーバーへのアクセス

  • MCP認証用のAPIキー

クイックスタート

1. クローンとセットアップ

git clone https://github.com/pzanna/email_mcp.git
cd email_mcp
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -r requirements.txt

2. 環境設定

cp .env.example .env
# Edit .env with your credentials

必要な環境変数:

# IMAP Configuration
IMAP_HOST=imap.gmail.com
IMAP_PORT=993
IMAP_USER=you@gmail.com
IMAP_PASSWORD=your-app-password
IMAP_SSL=true

# SMTP Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=you@gmail.com
SMTP_PASSWORD=your-app-password
# SMTP_STARTTLS mode: "none" (auto), "true" (force), "false" (disable)
SMTP_STARTTLS=true

# MCP Server Configuration
MCP_API_KEY=your-secret-api-key-here
MCP_HOST=127.0.0.1
MCP_PORT=8420
MCP_SERVER_NAME=email-mcp
MCP_BASE_URL=http://localhost:8420

# Optional
DEFAULT_FROM_NAME=Your Name
MAX_SEARCH_RESULTS=50
IMAP_POOL_SIZE=3

# Attachment Configuration
EMAIL_BASE_DIR=/path/to/workspace
MAX_ATTACHMENT_SIZE_MB=50

3. サーバーの実行

ローカル開発 (Mac/Linux):

source .venv/bin/activate
uvicorn main:app --host 127.0.0.1 --port 8420

サーバーへのアクセス:

  • MCPエンドポイント: http://localhost:8420/mcp

  • ヘルスチェック: http://localhost:8420/health

  • APIドキュメント: http://localhost:8420/docs

テスト

# Run all tests
pytest tests/ -v

# Run with coverage
pytest tests/ --cov=. --cov-report=html

# Run specific test file
pytest tests/test_integration.py -v

# Run specific test
pytest tests/test_send.py::test_send_email_plain_text -v

85以上のすべてのテストがパスするはずです。

使用例

認証

すべてのMCPエンドポイントには X-API-Key ヘッダーが必要です:

curl -H "X-API-Key: your-secret-api-key-here" \
  http://localhost:8420/mcp/tools

利用可能なツールの一覧表示

curl -X GET http://localhost:8420/mcp/tools \
  -H "X-API-Key: your-secret-api-key-here"

メールの検索

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "search_emails",
      "arguments": {
        "from": "user@example.com",
        "subject": "invoice",
        "since": "2024-01-01",
        "limit": 10
      }
    }
  }'

メールの送信

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "send_email",
      "arguments": {
        "to": ["recipient@example.com"],
        "subject": "Test Email",
        "body": "This is a test email.",
        "from_name": "My Name"
      }
    }
  }'

メールの読み取り

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "read_email",
      "arguments": {
        "uid": "12345",
        "folder": "INBOX"
      }
    }
  }'

メール添付ファイルのダウンロード

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "download_attachment",
      "arguments": {
        "uid": "12345",
        "attachment_index": 0,
        "folder": "INBOX",
        "filename_override": "renamed_file.pdf"
      }
    }
  }'

添付ファイルを EMAIL_BASE_DIR/attachments/email/downloads/ にダウンロードします。ファイルがベースディレクトリ内に留まるようセキュリティバリデーションが行われます。

添付ファイル付きメールの送信

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "send_email_with_attachments",
      "arguments": {
        "to": ["recipient@example.com"],
        "cc": ["manager@example.com"],
        "subject": "Monthly Report",
        "body": "Please find the reports attached.",
        "body_html": "<p>Please find the <strong>reports</strong> attached.</p>",
        "from_name": "John Doe",
        "attachment_paths": [
          "attachments/email/uploads/report1.pdf",
          "attachments/email/uploads/report2.xlsx"
        ]
      }
    }
  }'

ワークスペースディレクトリからファイルを添付します。完全なセキュリティバリデーションとサイズ制限の強制が適用されます。

添付ファイルの取り扱い

Email MCPサーバーは、ワークスペースベースのファイル管理による安全な添付ファイル処理を提供します。

ワークスペースディレクトリ構造

すべての添付ファイル操作は、設定されたワークスペースディレクトリ内に限定されます:

EMAIL_BASE_DIR/
└── attachments/
    └── email/
        ├── downloads/    # Downloaded email attachments
        └── uploads/      # Files ready to attach to outgoing emails

セキュリティ機能

  • ワークスペースの制限: すべてのファイル操作は EMAIL_BASE_DIR に制限されます

  • パストラバーサル保護: ワークスペース外のファイルへのアクセスを防止

  • ファイル名のサニタイズ: 危険な文字を削除し、予約名を処理

  • サイズ制限: ファイルごとおよび合計添付ファイルサイズの制限を設定可能

  • ファイルタイプのバリデーション: 添付ファイルのパスが実際のファイルを指していることを確認

ワークフローの例

ダウンロード → 送信ワークフロー:

  1. download_attachment を使用してメール添付ファイルを downloads/ に保存

  2. 必要に応じてファイルを uploads/ に移動またはコピー

  3. send_email_with_attachments を使用して uploads/ からファイルを送信

直接アップロードワークフロー:

  1. uploads/ ディレクトリにファイルを配置

  2. ワークスペース相対パスを使用して send_email_with_attachments を使用

設定

# Workspace directory (required for attachment operations)
EMAIL_BASE_DIR=/path/to/your/workspace

# Maximum attachment size per file (default: 50MB)
MAX_ATTACHMENT_SIZE_MB=50

デプロイ

systemdを使用したUbuntuサーバー

  1. サーバーへファイルをコピー:

scp -r email_mcp user@server:/home/user/
  1. Python環境のセットアップ:

ssh user@server
cd ~/email_mcp
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
  1. リモートアクセスの設定: .env を編集:

MCP_HOST=0.0.0.0  # Allow remote connections
MCP_BASE_URL=http://<your-server-ip>:8420  # Your server IP
  1. systemdサービスのインストール:

# Edit email-mcp.service to match your paths
sudo cp email-mcp.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable email-mcp
sudo systemctl start email-mcp
  1. ステータスの確認:

sudo systemctl status email-mcp
sudo journalctl -u email-mcp -f  # View logs

MCPクライアントの設定

MCPクライアントの設定に追加してください:

{
  "mcpServers": {
    "email": {
      "url": "http://localhost:8420/mcp",
      "headers": {
        "X-API-Key": "your-secret-api-key-here"
      }
    }
  }
}

リモートサーバーの場合は http://<your-server-ip>:8420/mcp を使用してください(サーバーのIPに置き換えてください)。

アーキテクチャ

email_mcp/
├── main.py                 # FastAPI application entry point (HTTP/SSE mode)
├── mcp_server.py           # Stdio MCP entry point (MCPB / Claude Desktop mode)
├── config.py               # Pydantic settings (env vars)
├── auth.py                 # API key authentication middleware
├── imap/
│   ├── client.py          # IMAP connection pool
│   ├── read.py            # list_folders, read_email
│   ├── search.py          # search_emails
│   ├── flags.py           # mark_email, move_email
│   └── attachments.py     # download_attachment
├── smtp/
│   ├── client.py          # send_email, reply_email
│   └── attachments.py     # send_email_with_attachments
├── tools/
│   ├── definitions.py     # MCP tool schemas
│   ├── handlers.py        # Tool request routing
│   └── mcp_routes.py      # MCP HTTP endpoints
├── utils/
│   └── attachment_utils.py # Secure file handling utilities
└── tests/                  # 85+ unit and integration tests

主要な設計パターン

  • コネクションプーリング: asyncio.Semaphore が同時IMAP接続を制限(デフォルト: 3)

  • エラーハンドリング: 構造化された例外がMCPエラーレスポンスにマッピングされます

  • メールスレッド: 返信チェーンのための In-Reply-To および References ヘッダー

  • マルチパートメッセージ: メッセージツリーを走査してテキスト/HTML/添付ファイルを抽出

  • バイナリ転送なし: 添付ファイルはメタデータのみを返します(ファイル名、サイズ、content_type)

トラブルシューティング

Gmail固有の設定

  1. IMAPを有効化: 設定 → メール転送とPOP/IMAP → IMAPを有効にする

  2. アプリパスワード: 通常のパスワードの代わりにアプリパスワードを使用

  3. Gmail SMTP: STARTTLSを使用して smtp.gmail.com:587 を使用

接続の問題

# Test IMAP connection
openssl s_client -connect imap.gmail.com:993

# Test SMTP connection
openssl s_client -starttls smtp -connect smtp.gmail.com:587

一般的なエラー

  • CONNECTION_TIMEOUT: IMAP_HOSTとIMAP_PORTを確認してください

  • AUTH_FAILED: 認証情報を確認し、Gmailの場合はアプリパスワードを使用してください

  • FOLDER_NOT_FOUND: フォルダー名はケースセンシティブです(list_folders で確認してください)

  • MESSAGE_NOT_FOUND: UIDが無効か、メッセージが削除された可能性があります

SMTPException - Connection already using TLS: 自動モードの場合は .env で SMTP_STARTTLS=none を設定してください。有効な値は none、true、false です。

開発

プロジェクト構造

  • imap/ - IMAPクライアントとツール(読み取り、検索、フラグ)

  • smtp/ - SMTPクライアントとツール(送信、返信)

  • tools/ - MCPエンドポイントハンドラーとスキーマ

  • tests/ - ユニットテストおよび統合テスト

開発環境での実行

# Auto-reload on file changes
uvicorn main:app --reload --host 127.0.0.1 --port 8420

# Debug mode with verbose logging
LOG_LEVEL=DEBUG uvicorn main:app --host 127.0.0.1 --port 8420

新しいツールの追加

  1. 適切なモジュールで入出力用のPydanticモデルを定義

  2. エラーハンドリングを含む非同期関数を実装

  3. tools/definitions.py にツールスキーマを追加

  4. tools/mcp_routes.py でディスパッチャーを接続

  5. TDDアプローチに従ってテストを作成

ライセンス

MIT

コントリビューション

コントリビューションを歓迎します!以下の点をお願いします:

  1. すべての新機能に対してテストを書く

  2. 既存のコードスタイル(black, isort, mypy)に従う

  3. 重要な変更についてはこのREADMEを更新する

  4. PRを提出する前にすべてのテストがパスすることを確認する

サポート

問題、質問、機能リクエストについては、GitHubでIssueを開いてください。

Related MCP Connectors