Skip to main content
Glama
cat-people-82

Email MCP Server

Email MCP Server

一个 Model Context Protocol (MCP) 服务器,提供通过 IMAP 和 SMTP 访问电子邮件的功能。使 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 安装(推荐)

使用此服务器最简单的方法是通过 MCPB 捆绑包——这是 Claude Desktop 的单文件安装方式。

1. 下载

从 最新版本 下载 email_mcp.mcpb。

2. 安装

双击 email_mcp.mcpb。Claude Desktop 将打开一个安装对话框。

3. 配置

在提示时填写您的邮件服务器凭据。所有值都存储在操作系统钥匙串中(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 关于该项目的邮件" "发送一封邮件给 bob@example.com,主题为 'Hello',正文为 'Hi Bob!'" "下载邮件 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:使用 smtp.gmail.com:587 并开启 STARTTLS

连接问题

# 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