电子邮件收发MCP服务器

基于FastMCP 2.0构建的MCP服务器,通过SMTP、POP3和IMAP协议实现电子邮件的发送和接收功能,适用于AI助手自动化邮件工作流。

  • by bedro96
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 bedro96/email-send-mcp

使用说明

电子邮件发送/接收MCP服务器

一种模型上下文协议(MCP)服务器,用于通过SMTP、POP3和IMAP发送和接收电子邮件。该服务器采用FastMCP 2.0构建,使Claude等AI助手能够与电子邮件服务进行交互,从而轻松实现电子邮件工作流程的自动化、收件箱的检查以及以编程方式发送消息。

🎯 什么是MCP?

模型上下文协议(MCP)是一个开放标准,使AI应用程序能够安全地连接到外部数据源和工具。该服务器实现了MCP,使AI助手能够:

  • 发送邮件 带附件,CC/BCC支持
  • 接收和阅读电子邮件 从IMAP/POP3服务器
  • 搜索和筛选 电子邮件
  • 与多个电子邮件提供商合作 (Gmail、Outlook、雅虎等)

非常适合与AI助手集成,如 克劳德桌面版,此服务器充当会话式AI和电子邮件基础设施之间的桥梁。

✨ 特征

📤 电子邮件发送(SMTP)

  • ✅ 发送带有已验证收件人地址的电子邮件
  • ✅ 支持CC(复写)和BCC(盲复写)
  • ✅ HTML和纯文本电子邮件正文
  • ✅ 文件附件支持大小验证
  • ✅ 可配置的发件人信息(姓名和电子邮件)
  • ✅ 对多个收件人进行批量电子邮件验证
  • ✅ 智能TLS/SSL连接处理

📥 电子邮件接收(IMAP/POP3)

  • ✅ 从支持完整文件夹的IMAP服务器检索电子邮件
  • ✅ POP3协议支持简单的电子邮件检索
  • ✅ 按邮箱/文件夹筛选(收件箱、已发送、草稿等)
  • ✅ 未读电子邮件过滤
  • ✅ 附件信息提取
  • ✅ 电子邮件元数据解析(发件人、主题、日期等)
  • ✅ 带长度限制的车身预览

🔒 电子邮件验证和安全

  • ✅ 符合RFC的电子邮件地址验证
  • ✅ 自动电子邮件规范化
  • ✅ 对多个收件人进行批量验证
  • ✅ 主要提供商的应用程序密码支持
  • ✅ 所有连接的TLS/SSL加密
  • ✅ 通过环境变量实现安全的凭据管理

🛡️ API密钥验证

  • ✅ x-api-key 通过ASGI中间件进行基于报头的身份验证
  • ✅ 不区分大小写的标题键匹配(X-Api-Key, x-api-key等等)
  • ✅ 生产模式强制认证;开发模式绕过它
  • ✅ /api/health 端点始终是公共的(不需要身份验证)
  • ✅ 可通过以下方式配置 APPLICATION_MODE 和 X-API-KEY 环境变量

📋 目录

🚀 快速开始

5分钟后开始!请按照以下步骤操作:

# 1. Clone and install
git clone https://github.com/bedro96/email-send-mcp.git
cd email-send-mcp
pip install -e .

# 2. Configure email credentials
cp .env.example .env
# Edit .env with your email provider settings

# 3. Run the server
python main.py

有关详细的快速启动说明,请参阅 QUICKSTART.md.

📦 安装

先决条件

  • Python 3.11或更高版本 - 下载Python
  • 电子邮件账户 具有SMTP/IMAP访问权限(Gmail、Outlook、Yahoo等)
  • 应用程序密码 适用于您的电子邮件提供商(适用于Gmail、Outlook、Yahoo)

方法1:使用紫外线(推荐)

紫外线 是一个快速的Python包管理器,简化了依赖关系管理。

# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone the repository
git clone https://github.com/bedro96/email-send-mcp.git
cd email-send-mcp

# Install dependencies
uv pip install -e .

# For development with testing tools
uv pip install -e ".[dev]"

方法2:使用pip

# Clone the repository
git clone https://github.com/bedro96/email-send-mcp.git
cd email-send-mcp

# Install dependencies
pip install -e .

# For development (optional)
pip install -e ".[dev]"

验证安装

# Check if dependencies are installed
python -c "import fastmcp; print('FastMCP version:', fastmcp.__version__)"

⚙️ 配置

步骤1:创建环境文件

  1. 复制示例环境文件:
cp .env.example .env
  1. 编辑 .env 使用您的电子邮件服务器凭据:
# SMTP Configuration (for sending emails)
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@example.com
SMTP_PASSWORD=your-app-password
SMTP_USE_TLS=true

# IMAP Configuration (for receiving emails)
IMAP_SERVER=imap.gmail.com
IMAP_PORT=993
IMAP_USERNAME=your-email@example.com
IMAP_PASSWORD=your-app-password
IMAP_USE_SSL=true

# POP3 Configuration (alternative for receiving emails)
POP3_SERVER=pop.gmail.com
POP3_PORT=995
POP3_USERNAME=your-email@example.com
POP3_PASSWORD=your-app-password
POP3_USE_SSL=true

# Email Settings
DEFAULT_FROM_EMAIL=your-email@example.com
DEFAULT_FROM_NAME=MCP Email Server
MAX_ATTACHMENT_SIZE_MB=25

# Server Configuration
LOG_LEVEL=INFO
DEBUG=false

# Mode: Development (auth bypassed) or Production (auth enforced)
APPLICATION_MODE=Production

# API Key for x-api-key header authentication
X-API-KEY=your-strong-api-key-here

步骤2:电子邮件提供商设置

Gmail设置(最常见)

对于Gmail,您需要:

  1. 启用双因素身份验证

  2. 生成应用程序密码

    • 访问 应用程序密码
    • 选择“邮件”和您的设备
    • 复制生成的16个字符的密码
    • 在您的 .env 文件
  3. 启用IMAP访问 (用于接收电子邮件)

    • 打开Gmail→ 设置→ 查看所有设置
    • 转到“转发和POP/IMAP”选项卡
    • 启用IMAP
    • 保存更改

Gmail配置:

SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=xxxx xxxx xxxx xxxx  # 16-character app password
SMTP_USE_TLS=true

IMAP_SERVER=imap.gmail.com
IMAP_PORT=993
IMAP_USERNAME=your-email@gmail.com
IMAP_PASSWORD=xxxx xxxx xxxx xxxx  # Same app password
IMAP_USE_SSL=true

DEFAULT_FROM_EMAIL=your-email@gmail.com

其他电子邮件提供商

有关Outlook、Yahoo、ProtonMail、iCloud和自定义SMTP服务器的配置详细信息,请参阅 电子邮件_视频.md.

配置参数说明

参数 说明 默认值 必填
SMTP_SERVER SMTP服务器主机名 SMTP.gmail.com 是(用于发送)
SMTP_PORT SMTP服务器端口(TLS为587,SSL为465) 587 是(用于发送)
SMTP_USERNAME SMTP身份验证用户名(通常是电子邮件) - 是(用于发送)
SMTP_PASSWORD SMTP身份验证密码(使用应用程序密码) - 是(用于发送)
SMTP_USE_TLS SMTP使用STARTTLS(建议用于端口587) true 否
IMAP_SERVER IMAP服务器主机名 IMAP.gmail.com 是(用于接收)
IMAP_PORT IMAP服务器端口(SSL为993) 993 是(用于接收)
IMAP_USERNAME IMAP身份验证用户名 - 是(用于接收)
IMAP_PASSWORD IMAP身份验证密码 - 是(用于接收)
IMAP_USE_SSL IMAP使用SSL true 否
POP3_SERVER POP3服务器主机名 pop.gmail.com 否
POP3_PORT POP3服务器端口(SSL为995) 995 否
POP3_USERNAME POP3身份验证用户名 - 否
POP3_PASSWORD POP3身份验证密码 - 否
POP3_USE_SSL 对POP3使用SSL true 否
DEFAULT_FROM_EMAIL 默认发件人电子邮件地址 - 是
DEFAULT_FROM_NAME 默认发件人显示名称 MCP电子邮件服务器 否
MAX_ATTACHMENT_SIZE_MB 最大附件大小(MB) 25 否
LOG_LEVEL 日志记录级别(调试、信息、警告、错误) 信息 否
DEBUG 启用调试模式 false 否

安全最佳实践

⚠️ 重要安全注意事项:

  1. 永不承诺 .env 文件 具有版本控制的真实凭据
  2. 始终使用应用程序密码 而不是您的主帐户密码
  3. 启用双因素身份验证 在您的电子邮件帐户上
  4. 使用TLS/SSL 适用于所有电子邮件连接
  5. 安全地存储机密 在生产环境中(Azure密钥库、AWS密钥管理器等)
  6. 定期轮换密码 并撤销未使用的应用程序密码
  7. 限制权限 只做必要的事

🛡️ 认证

服务器使用 x-api-key 由控制的基于标头的身份验证 APPLICATION_MODE 环境变量。

运作原理

APPLICATION_MODE 价值 行为
Production 每一个请求 /mcp 必须包含有效的 x-api-key 头球服务器 拒绝开始 如果 X-API-KEY 未设置。
Development (默认) 身份验证为 绕过 --允许所有请求

这 /api/health 端点是 始终公开 无论模式如何。

标题规则

  • 密钥匹配不区分大小写: x-api-key, X-Api-Key, X-API-KEY 都被接受了。
  • 值匹配准确:提供的值必须匹配 X-API-KEY 在 .env 确切地说(区分大小写)。

配置

# .env
APPLICATION_MODE=Production          # or Development
X-API-KEY=your-strong-secret-key

迁移说明: 使用的早期版本 MODE 而不是 APPLICATION_MODE。将变量重命名为 .env 升级时。

测试身份验证

# Without key (Production mode) → 401
curl https://<host>/mcp

# With correct key → 200 / normal MCP response
curl -H "x-api-key: your-strong-secret-key" https://<host>/mcp

# Health check — always works without a key
curl https://<host>/api/health

🛠️ MCP工具(功能)

此服务器公开 3个强大的MCP工具 AI助手可以使用它与电子邮件服务进行交互。下面详细记录了每个工具。

1. send_email -通过SMTP发送电子邮件

发送完全支持附件、CC/BCC和HTML格式的电子邮件。

功能签名:

async def send_email(
    recipient: str,              # Required: Primary recipient email
    subject: str,                # Required: Email subject/title
    body: str,                   # Required: Email body content
    attachments: List[str] = None,  # Optional: File paths to attach
    cc: List[str] = None,        # Optional: CC recipients
    bcc: List[str] = None,       # Optional: BCC recipients
    is_html: bool = False        # Optional: HTML formatting flag
) -> str

参数:

参数 类型 必填 说明
recipient str ✅ 是 主要收件人电子邮件地址(根据RFC标准验证)
subject str ✅ 是 电子邮件主题行
body str ✅ 是 电子邮件正文内容(纯文本或HTML)
attachments List[str] ❌ 否 要附加的绝对文件路径列表(验证大小和是否存在)
cc List[str] ❌ 否 抄送收件人电子邮件地址列表
bcc List[str] ❌ 否 盲拷贝收件人电子邮件地址列表
is_html bool ❌ 否 设置为 true 对于HTML格式的电子邮件(默认值: false 纯文本)

退货:

  • 成功:格式化的确认消息,包含交付详细信息
  • 错误:解释错误原因的错误消息

Claude中的示例用法:

Please send an email to john@example.com with the subject "Project Update" 
and body "The quarterly report is attached." Attach the file /path/to/report.pdf

示例响应:

✅ Email sent successfully!
Recipient: john@example.com
Subject: Project Update
CC: None
BCC: None
Attachments: 1

特征:

  • ✅ 自动电子邮件地址验证和规范化
  • ✅ 带有大小验证的文件附件(默认最大值:25MB)
  • ✅ 支持多个CC和BCC收件人
  • ✅ 具有正确MIME编码的HTML电子邮件支持
  • ✅ 智能SMTP连接处理(TLS/SSL)
  • ✅ 用于故障排除的详细错误消息

2. receive_emails_imap -通过IMAP检索电子邮件

使用高级过滤选项从IMAP服务器检索和读取电子邮件。

功能签名:

async def receive_emails_imap(
    mailbox: str = "INBOX",      # Mailbox/folder to read from
    limit: int = 10,             # Maximum emails to retrieve
    unread_only: bool = False    # Filter for unread only
) -> str

参数:

参数 类型 必填 默认 说明
mailbox str ❌ 没有 "INBOX" 邮箱/文件夹名称(收件箱、已发送、草稿等)
limit int ❌ 没有 10 要检索的最大电子邮件数(1-100)
unread_only bool ❌ 没有 false 仅检索未读邮件

退货:

  • 带有元数据和正文预览的格式化电子邮件列表
  • 每封电子邮件包括:ID、发件人、收件人、主题、日期、正文预览、附件

Claude中的示例用法:

Please check my inbox and show me the last 5 unread emails

示例响应:

📬 Retrieved 5 email(s):

--- Email 1 ---
ID: 12345
From: alice@company.com
To: you@example.com
Subject: Meeting Tomorrow
Date: Mon, 10 Nov 2025 10:30:00 +0000
Attachments: 1
  - agenda.pdf (application/pdf)
Body Preview: Hi, just a reminder about our meeting tomorrow at 2 PM. 
I've attached the agenda for your review...
Body Length: 450 characters

--- Email 2 ---
[...]

特征:

  • ✅ 支持所有IMAP文件夹(收件箱、已发送、草稿、自定义文件夹)
  • ✅ 仅未读筛选
  • ✅ 附件检测和元数据提取
  • ✅ 电子邮件正文预览(前200个字符)
  • ✅ 完整的元数据解析(发件人、收件人、日期、主题)
  • ✅ 处理多种编码和国际字符
  • ✅ 安全SSL/TLS连接

支持的邮箱名称:

  • INBOX -主收件箱
  • Sent -已发送电子邮件
  • Drafts -消息草稿
  • Trash -已删除邮件
  • Spam 或 Junk -垃圾邮件文件夹
  • 用户创建的自定义文件夹

3. receive_emails_pop3 -通过POP3检索电子邮件

使用更简单的POP3协议检索电子邮件(注意:POP3的功能不如IMAP丰富)。

功能签名:

def receive_emails_pop3(
    limit: int = 10              # Maximum emails to retrieve
) -> str

参数:

参数 类型 必填 默认 说明
limit int ❌ 没有 10 要检索的最大电子邮件数

退货:

  • 格式化的电子邮件列表(类似于IMAP输出)

Claude中的示例用法:

Fetch my last 10 emails using POP3

特征:

  • ✅ 简单的电子邮件检索
  • ✅ 附件检测
  • ✅ 电子邮件元数据解析
  • ✅ SSL/TLS支持

注: POP3与IMAP相比有局限性:

  • ❌ 不支持文件夹(仅从主收件箱检索)
  • ❌ 无未读筛选
  • ❌ 对于大型邮箱效率较低
  • ✅ 尽可能使用IMAP以获得更好的功能

工具比较

特点 send_email receive_emails_imap receive_emails_pop3
主要功能 发送电子邮件 接收电子邮件 接收邮件
协议 SMTP IMAP POP3
附件支持 ✅ 发送 ✅ 检测 ✅ 检测
HTML支持 ✅ 是 ✅ 是 ✅ 是的
文件夹支持 不适用 ✅ 是 ❌ 没有
未读筛选 不适用 ✅ 是 ❌ 没有
CC/BCC支持 ✅ 是 不适用 不适用
用例 发送自动电子邮件 完整的电子邮件管理 简单的电子邮件检索

💡 使用示例

运行MCP服务器

以HTTP模式启动服务器(用于MCP客户端连接):

python main.py

服务器将:

  1. 从加载配置 .env 文件
  2. 初始化SMTP、IMAP和POP3服务
  3. 开始收听 http://0.0.0.0:8888/mcp
  4. 公开MCP工具供AI助手使用
  5. 将所有活动记录到控制台和日志文件中

服务器输出:

2025-11-10 15:57:03 - email-send-mcp - INFO - Starting Email Send/Receive MCP Server...
2025-11-10 15:57:03 - email-send-mcp - INFO - Configuration values set from environment variables.
2025-11-10 15:57:03 - email-send-mcp - INFO - EmailSender service initialized.
2025-11-10 15:57:03 - email-send-mcp - INFO - EmailReceiver service initialized.
2025-11-10 15:57:03 - email-send-mcp - INFO - Server running on http://0.0.0.0:8888/mcp

示例1:发送一封简单的文本电子邮件

自然语言请求(通过Claude):

Please send an email to colleague@company.com with the subject "Team Meeting" 
and tell them the meeting is scheduled for tomorrow at 2 PM.

发生了什么:

  • 克劳德使用 send_email 工具
  • 电子邮件地址已验证
  • 电子邮件通过配置的SMTP服务器发送
  • 确认已返回

MCP工具调用(幕后):

send_email(
    recipient="colleague@company.com",
    subject="Team Meeting",
    body="The meeting is scheduled for tomorrow at 2 PM."
)

答复:

✅ Email sent successfully!
Recipient: colleague@company.com
Subject: Team Meeting
CC: None
BCC: None
Attachments: 0

示例2:发送带有附件的HTML电子邮件

自然语言请求:

Send an email to team@company.com with subject "Quarterly Report" 
and include the report.pdf file. Use HTML formatting with a professional header.

MCP工具调用:

send_email(
    recipient="team@company.com",
    subject="Quarterly Report",
    body="""
    <html>
        <body>
            <h1>Quarterly Report - Q4 2025</h1>
            <p>Dear Team,</p>
            <p>Please find attached the quarterly report for your review.</p>
            <p>Best regards,<br>Management</p>
        </body>
    </html>
    """,
    attachments=["/path/to/report.pdf"],
    is_html=True
)

示例3:使用CC和BCC发送电子邮件

自然语言请求:

Email the project update to john@company.com, CC alice@company.com 
and bob@company.com, and BCC the manager@company.com

MCP工具调用:

send_email(
    recipient="john@company.com",
    subject="Project Update",
    body="The project is on track and will be completed by the deadline.",
    cc=["alice@company.com", "bob@company.com"],
    bcc=["manager@company.com"]
)

示例4:检查未读电子邮件

自然语言请求:

Show me my unread emails from the last week

MCP工具调用:

receive_emails_imap(
    mailbox="INBOX",
    limit=20,
    unread_only=True
)

答复:

📬 Retrieved 3 email(s):

--- Email 1 ---
ID: 12345
From: client@example.com
To: you@company.com
Subject: Question about Invoice
Date: Mon, 09 Nov 2025 14:30:00 +0000
Body Preview: Hi, I have a question about invoice #12345. Could you please clarify the charges for...
Body Length: 320 characters

[More emails...]

示例5:检查特定电子邮件文件夹

自然语言请求:

Check my Sent folder and show me the last 5 emails I sent

MCP工具调用:

receive_emails_imap(
    mailbox="Sent",
    limit=5,
    unread_only=False
)

示例6:检索带有附件的电子邮件

自然语言请求:

Show me emails with attachments from my inbox

MCP工具调用:

receive_emails_imap(
    mailbox="INBOX",
    limit=10,
    unread_only=False
)

响应(显示附件信息):

📬 Retrieved 2 email(s):

--- Email 1 ---
ID: 98765
From: partner@company.com
To: you@example.com
Subject: Contract Documents
Date: Tue, 08 Nov 2025 16:45:00 +0000
Attachments: 2
  - contract.pdf (application/pdf)
  - terms.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)
Body Preview: Please review the attached contract documents...

示例7:使用POP3进行简单检索

自然语言请求:

Get my last 5 emails using POP3

MCP工具调用:

receive_emails_pop3(limit=5)

程序化使用(Python)

如果你想在Python中直接使用电子邮件服务(没有MCP):

import asyncio
from src.services.email_sender import EmailSender
from src.services.email_receiver import EmailReceiver

async def main():
    # Send an email
    sender = EmailSender()
    result = await sender.send_email(
        recipient="user@example.com",
        subject="Test Email",
        body="This is a test message"
    )
    print(result)
    
    # Receive emails
    receiver = EmailReceiver()
    result = await receiver.receive_emails_imap(
        mailbox="INBOX",
        limit=5,
        unread_only=True
    )
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

有关更多示例,请参见 examples.py 在存储库中。

🧪 测试

该项目包括对验证器、配置和核心功能的全面测试。

运行测试

运行所有测试

# Basic test run
pytest tests/ -v

# Run with detailed output
pytest tests/ -vv

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

# Run tests in parallel (faster)
pytest tests/ -n auto

运行特定测试文件

# Test email validators only
pytest tests/test_validators.py -v

# Test configuration management
pytest tests/test_config.py -v

# Test specific function
pytest tests/test_validators.py::TestEmailValidation::test_validate_valid_email -v

测试覆盖率

该项目包括以下测试:

✅ 电子邮件验证 (tests/test_validators.py)

  • 有效的电子邮件地址验证
  • 无效的电子邮件检测(缺少@、无效域等)
  • 电子邮件规范化
  • 批量电子邮件验证
  • 带有姓名的电子邮件格式

✅ 配置管理 (tests/test_config.py)

  • 从环境加载设置
  • 默认值验证
  • 端口号验证
  • 字段类型验证

✅ SMTP测试 (test_smtp.py, test_smtp_variations.py)

  • SMTP连接测试
  • 电子邮件发送变体
  • 不同的提供商配置

✅ 集成测试 (test_kakao_specific.py)

  • 供应商特定测试
  • 现实世界场景

测试输出示例

$ pytest tests/ -v

============================= test session starts ==============================
tests/test_validators.py::TestEmailValidation::test_validate_valid_email PASSED
tests/test_validators.py::TestEmailValidation::test_validate_invalid_email_no_at PASSED
tests/test_validators.py::TestEmailValidation::test_validate_email_with_dots PASSED
tests/test_validators.py::TestEmailValidation::test_validate_email_with_plus PASSED
tests/test_validators.py::TestEmailValidation::test_validate_multiple_emails PASSED
tests/test_validators.py::TestEmailValidation::test_format_email_with_name PASSED
tests/test_config.py::TestSettings::test_default_values PASSED
tests/test_config.py::TestSettings::test_port_validation PASSED
============================== 8 passed in 0.45s ===============================

编写新测试

添加新功能时,请按照以下模式进行测试:

# tests/test_my_feature.py
import pytest
from src.services.my_service import MyService

class TestMyFeature:
    """Test suite for my new feature."""
    
    def test_basic_functionality(self):
        """Test basic feature operation."""
        service = MyService()
        result = service.do_something()
        assert result is not None
    
    @pytest.mark.asyncio
    async def test_async_functionality(self):
        """Test async feature operation."""
        service = MyService()
        result = await service.do_something_async()
        assert result["status"] == "success"

集成测试

对于使用真实电子邮件服务器进行测试:

  1. 创建测试电子邮件帐户 (不要使用您的主帐户)
  2. 设置测试凭据 在 .env.test:
    SMTP_SERVER=smtp.gmail.com
    SMTP_PORT=587
    SMTP_USERNAME=test-account@gmail.com
    SMTP_PASSWORD=test-app-password
    
  3. 运行集成测试 (未包含在默认测试套件中):
    pytest tests/integration/ -v --env-file=.env.test
    

手动测试

您可以手动测试MCP服务器:

  1. 启动服务器:

    python main.py
    
  2. 卷曲测试 (健康检查):

    curl http://localhost:8888/api/health
    # Expected: {"status":"ok"}
    
  3. 测试电子邮件发送 (使用示例.py):

    python examples.py
    

测试检查表

在提交代码之前:

  • []所有现有测试均通过(pytest tests/ -v)
  • []为新功能添加了新测试
  • []保持或改进代码覆盖率
  • []测试遵循命名约定(test_*.py, Test* 班级)
  • []异步测试使用 @pytest.mark.asyncio 装饰器
  • []集成测试单独标记

持续集成

此项目已准备好进行CI/CD集成。GitHub操作工作流示例:

name: Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      - name: Install dependencies
        run: |
          pip install -e ".[dev]"
      - name: Run tests
        run: |
          pytest tests/ -v --cov=src --cov-report=xml
      - name: Upload coverage
        uses: codecov/codecov-action@v3

🔬 烟雾测试结果

针对生产Azure容器应用程序部署执行的实时烟雾测试:

生产URL: https://email-send-mcp.victoriousdune-f6c83ffa.koreacentral.azurecontainerapps.io

如何运行测试

测试A——未经身份验证的请求(预计部署后为401):

curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST \
  https://email-send-mcp.victoriousdune-f6c83ffa.koreacentral.azurecontainerapps.io/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
# Expected: HTTP 401

测试B-错误的API密钥(预期401):

curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST \
  https://email-send-mcp.victoriousdune-f6c83ffa.koreacentral.azurecontainerapps.io/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "x-api-key: wrongkey" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
# Expected: HTTP 401

测试C——经过身份验证的send_email(预计200多次投递):

curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST \
  https://email-send-mcp.victoriousdune-f6c83ffa.koreacentral.azurecontainerapps.io/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "x-api-key: $X_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "send_email",
      "arguments": {
        "recipient": "kunhoko@kakao.com",
        "subject": "Smoke testing",
        "body": "Do you see this message! It is test message from Github Copilot"
      }
    }
  }'
# Expected: HTTP 200, email delivered

测试D——健康检查(始终公开,预计200):

curl -s -w "\nHTTP_STATUS:%{http_code}" \
  https://email-send-mcp.victoriousdune-f6c83ffa.koreacentral.azurecontainerapps.io/api/health
# Expected: HTTP 200 {"status":"ok"}

测试E——不区分大小写的标题键(200除外):

curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST \
  https://email-send-mcp.victoriousdune-f6c83ffa.koreacentral.azurecontainerapps.io/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "X-Api-Key: $X_API_KEY" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
# Expected: HTTP 200 (mixed-case key accepted)

本地验证结果(提交 2fbb904)

通过在本地运行服务器来验证身份验证中间件 APPLICATION_MODE=Production:

INFO - Running in Production mode. Authentication enforced.
测试 描述 预期HTTP 结果 响应
D GET /api/health --无密钥 200 ✅ 通过 {"status":"ok"}
A. POST /mcp --没有 x-api-key 标题 401 ✅ 通过 {"error":"Unauthorized","detail":"Invalid or missing x-api-key header"}
B POST /mcp --错了 x-api-key 值 401 ✅ 通过 {"error":"Unauthorized","detail":"Invalid or missing x-api-key header"}
E POST /mcp --混合案例 X-Api-Key header(正确值) auth-pass ✅ 通过 已接受授权;MCP层返回400(无会话),而不是401
C 已验证 send_email 到 kunhoko@kakao.com 200+交付✅ 通过 {"status":"success","message":"Email sent successfully to kunhoko@kakao.com"}

确认电子邮件送达

电子邮件已成功送达 kunhoko@kakao.com:

  • 主题: 冒烟测试
  • 主体: 你看到这条消息了吗!这是来自Github Copilot的测试消息
  • 发送方式: SMTP(Kakao邮件)

生产部署状态

注: CI/CD管道需要Azure租户托管中的联合身份凭据 kunhoregistry.azurecr.io 和 azureaiagent-rg。一旦为受试者添加了凭证 repo:bedro96/email-send-mcp:ref:refs/heads/main,管道将在每次向main推送时自动部署。 预计所有5个测试都将以相同的方式通过生产URL。

🔌 与MCP客户端集成

此服务器与任何MCP客户端兼容。以下是针对热门客户的详细说明。

Claude桌面集成

克劳德桌面版 是Anthropic的官方桌面应用程序,支持MCP服务器。

安装说明

  1. 查找Claude桌面配置文件

    配置文件位置因操作系统而异:

    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • 窗户: %APPDATA%\Claude\claude_desktop_config.json
    • Linux: ~/.config/Claude/claude_desktop_config.json
  2. 将电子邮件MCP服务器添加到配置中

    选项A:使用环境变量 (推荐)

    {
      "mcpServers": {
        "email": {
          "command": "python",
          "args": ["/absolute/path/to/email-send-mcp/main.py"],
          "env": {
            "SMTP_SERVER": "smtp.gmail.com",
            "SMTP_PORT": "587",
            "SMTP_USERNAME": "your-email@gmail.com",
            "SMTP_PASSWORD": "your-app-password",
            "IMAP_SERVER": "imap.gmail.com",
            "IMAP_PORT": "993",
            "IMAP_USERNAME": "your-email@gmail.com",
            "IMAP_PASSWORD": "your-app-password",
            "DEFAULT_FROM_EMAIL": "your-email@gmail.com"
          }
        }
      }
    }
    

    选项B:使用.env文件 (更简单)

    {
      "mcpServers": {
        "email": {
          "command": "python",
          "args": ["/absolute/path/to/email-send-mcp/main.py"],
          "cwd": "/absolute/path/to/email-send-mcp"
        }
      }
    }
    

    此选项假定您有 .env 项目目录中的文件。

  3. 重新启动克劳德桌面

    更新配置后,完全退出并重新启动Claude Desktop。

  4. 验证集成

    在Claude Desktop中,您应该看到可用的电子邮件工具。试着问:

    Can you help me send an email?
    

    克劳德应该认识到它有权访问 send_email 工具。

在Claude Desktop中使用电子邮件工具

配置后,您可以使用自然语言与电子邮件交互:

发送电子邮件:

  • “发送电子邮件至john@example.com主题为“会议”,并告诉他明天的会议”
  • “向团队发送有关项目更新的电子邮件”
  • “发送一封附有季度报告的电子邮件”

接收电子邮件:

  • “检查我的收件箱中是否有未读电子邮件”
  • “显示我最近收到的10封电子邮件”
  • “我有哪些带附件的电子邮件?”
  • “检查我的已发送文件夹”

其他MCP客户端

此服务器适用于任何兼容MCP的客户端:

自定义MCP客户端

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    server_params = StdioServerParameters(
        command="python",
        args=["/path/to/email-send-mcp/main.py"],
        env={
            "SMTP_SERVER": "smtp.gmail.com",
            # ... other env vars
        }
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the connection
            await session.initialize()
            
            # List available tools
            tools = await session.list_tools()
            print("Available tools:", tools)
            
            # Call send_email tool
            result = await session.call_tool(
                "send_email",
                arguments={
                    "recipient": "user@example.com",
                    "subject": "Test",
                    "body": "Hello from MCP client!"
                }
            )
            print(result)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

HTTP MCP客户端

服务器还支持基于web的集成的HTTP传输:

// JavaScript/Node.js example
const response = await fetch('http://localhost:8888/mcp', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    jsonrpc: '2.0',
    method: 'tools/call',
    params: {
      name: 'send_email',
      arguments: {
        recipient: 'user@example.com',
        subject: 'Test Email',
        body: 'Hello from HTTP client!'
      }
    },
    id: 1
  })
});

const result = await response.json();
console.log(result);

MCP客户端的环境变量参考

配置MCP客户端时,需要以下环境变量:

所需最小变量:

{
  "SMTP_SERVER": "smtp.gmail.com",
  "SMTP_PORT": "587",
  "SMTP_USERNAME": "your-email@gmail.com",
  "SMTP_PASSWORD": "your-app-password",
  "DEFAULT_FROM_EMAIL": "your-email@gmail.com"
}

对于电子邮件接收(可选):

{
  "IMAP_SERVER": "imap.gmail.com",
  "IMAP_PORT": "993",
  "IMAP_USERNAME": "your-email@gmail.com",
  "IMAP_PASSWORD": "your-app-password"
}

MCP集成故障排除

问题:工具未出现在Claude Desktop中

  • 解决方案:验证配置文件路径是否正确
  • 解决方案:检查Python路径是否为绝对路径
  • 解决方案:配置更改后重新启动Claude Desktop

问题:“找不到模块”错误

  • 解决方案:确保安装了依赖项(pip install -e .)
  • 解决方案:使用完整的Python路径(例如。, /usr/local/bin/python3)

问题:身份验证错误

  • 解决方案:验证环境变量是否设置正确
  • 解决方案:检查是否使用了应用程序密码(不是常规密码)
  • 解决方案:验证SMTP/IMAP凭据是否正确

问题:服务器未启动

  • 解决方案:检查日志 logs/ 目录
  • 解决方案:验证 .env 文件存在并且可读
  • 解决方案:手动测试服务器: python main.py

🐳 Docker 部署

Docker提供了一种容器化的方式来运行电子邮件MCP服务器,确保不同环境之间的一致性。

先决条件

  • Docker已安装(获取Docker)
  • Docker Compose(可选,用于多容器设置)

Docker快速入门

第一步:构建Docker镜像

docker build -t email-send-mcp .

这将创建一个安装了所有依赖项的Docker镜像。

步骤2:运行容器

选项A:使用环境变量

docker run -d \
  --name email-mcp \
  -p 8888:8888 \
  -e SMTP_SERVER=smtp.gmail.com \
  -e SMTP_PORT=587 \
  -e SMTP_USERNAME=your-email@gmail.com \
  -e SMTP_PASSWORD=your-app-password \
  -e IMAP_SERVER=imap.gmail.com \
  -e IMAP_PORT=993 \
  -e IMAP_USERNAME=your-email@gmail.com \
  -e IMAP_PASSWORD=your-app-password \
  -e DEFAULT_FROM_EMAIL=your-email@gmail.com \
  email-send-mcp

选项B:使用.env文件(推荐)

docker run -d \
  --name email-mcp \
  -p 8888:8888 \
  --env-file .env \
  email-send-mcp

步骤3:验证容器是否正在运行

# Check container status
docker ps

# View logs
docker logs email-mcp

# Follow logs in real-time
docker logs -f email-mcp

# Test health endpoint
curl http://localhost:8888/api/health

Docker编写设置

为了便于管理,请使用Docker Compose:

docker-compose.yml:

version: '3.8'

services:
  email-mcp:
    build: .
    container_name: email-send-mcp
    ports:
      - "8888:8888"
    env_file:
      - .env
    restart: unless-stopped
    volumes:
      - ./logs:/app/logs
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8888/api/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

从Docker Compose开始:

# Start in background
docker-compose up -d

# View logs
docker-compose logs -f

# Stop
docker-compose down

# Rebuild and restart
docker-compose up -d --build

Docker管理命令

# Stop the container
docker stop email-mcp

# Start the container
docker start email-mcp

# Restart the container
docker restart email-mcp

# Remove the container
docker rm email-mcp

# Remove the image
docker rmi email-send-mcp

# View container logs
docker logs email-mcp --tail 100

# Execute commands inside container
docker exec -it email-mcp /bin/bash

# Inspect container
docker inspect email-mcp

生产Docker最佳实践

  1. 使用多阶段构建 (已在Dockerfile中)
  2. 以非Root用户身份运行 (已配置)
  3. 使用健康检查 (参见Docker Compose示例)
  4. 将日志装载为卷 为了坚持
  5. 使用秘密管理 用于生产凭证
  6. 设置资源限制:
docker run -d \
  --name email-mcp \
  --memory="512m" \
  --cpus="0.5" \
  --env-file .env \
  email-send-mcp

☁️ Azure容器应用部署

将电子邮件MCP服务器部署到Azure容器应用程序,以实现可扩展的无服务器托管。

先决条件

部署步骤

第一步:登录Azure

az login
az account set --subscription <your-subscription-id>

步骤2:创建资源组

az group create \
  --name email-mcp-rg \
  --location eastus

步骤3:创建Azure容器注册表(ACR)

# Create ACR
az acr create \
  --resource-group email-mcp-rg \
  --name emailmcpacr \
  --sku Basic

# Login to ACR
az acr login --name emailmcpacr

步骤4:构建图像并将其推送到ACR

# Build and push in one command
az acr build \
  --registry emailmcpacr \
  --image email-send-mcp:latest \
  .

# Or build locally and push
docker build -t emailmcpacr.azurecr.io/email-send-mcp:latest .
docker push emailmcpacr.azurecr.io/email-send-mcp:latest

步骤5:创建容器应用程序环境

# Create environment
az containerapp env create \
  --name email-mcp-env \
  --resource-group email-mcp-rg \
  --location eastus

步骤6:部署容器应用程序

az containerapp create \
  --name email-send-mcp \
  --resource-group email-mcp-rg \
  --environment email-mcp-env \
  --image emailmcpacr.azurecr.io/email-send-mcp:latest \
  --target-port 8888 \
  --ingress external \
  --registry-server emailmcpacr.azurecr.io \
  --cpu 0.5 \
  --memory 1Gi \
  --min-replicas 1 \
  --max-replicas 3 \
  --secrets \
    smtp-password=<your-app-password> \
    imap-password=<your-app-password> \
  --env-vars \
    SMTP_SERVER=smtp.gmail.com \
    SMTP_PORT=587 \
    SMTP_USERNAME=secretref:smtp-password \
    SMTP_PASSWORD=secretref:smtp-password \
    IMAP_SERVER=imap.gmail.com \
    IMAP_PORT=993 \
    IMAP_USERNAME=secretref:imap-password \
    IMAP_PASSWORD=secretref:imap-password \
    DEFAULT_FROM_EMAIL=your-email@gmail.com

步骤7:获取应用程序URL

az containerapp show \
  --name email-send-mcp \
  --resource-group email-mcp-rg \
  --query properties.configuration.ingress.fqdn

Azure容器应用功能

✅ 自动缩放: 根据HTTP流量自动扩展 ✅ 零停机时间: 通过滚动更新实现无缝部署 ✅ 内置负载平衡: 跨副本分发流量 ✅ 默认HTTPS: 自动SSL/TLS证书 ✅ 秘密管理: 安全的凭证存储 ✅ 监控: 与Azure Monitor和应用程序洞察集成

更新部署

# Update with new image
az containerapp update \
  --name email-send-mcp \
  --resource-group email-mcp-rg \
  --image emailmcpacr.azurecr.io/email-send-mcp:v2

# Update environment variables
az containerapp update \
  --name email-send-mcp \
  --resource-group email-mcp-rg \
  --set-env-vars LOG_LEVEL=DEBUG

监控和日志

# View logs
az containerapp logs show \
  --name email-send-mcp \
  --resource-group email-mcp-rg \
  --follow

# View metrics
az monitor metrics list \
  --resource /subscriptions/<subscription-id>/resourceGroups/email-mcp-rg/providers/Microsoft.App/containerApps/email-send-mcp \
  --metric-names HttpRequestsCount

成本优化

  • 使用消费计划(只为你使用的东西付费)
  • 设置适当的最小/最大副本
  • 根据指标配置比例规则
  • 为可预测的工作负载使用预留容量

安全最佳实践

  1. 使用Azure密钥库 为了秘密
  2. 启用托管身份 用于ACR身份验证
  3. 使用专用端点 仅供内部访问
  4. 配置CORS 政策
  5. 启用Azure AD身份验证 用于API访问
  6. 使用ExpressRoute集成 增强安全性

🏗️ 建筑

系统架构

┌─────────────────────────────────────────────────────────────┐
│                     MCP Client Layer                         │
│  (Claude Desktop, Custom Clients, Web Applications)         │
└────────────────────────┬────────────────────────────────────┘
                         │ MCP Protocol (HTTP/Stdio)
                         │
┌────────────────────────▼────────────────────────────────────┐
│                  FastMCP Server (main.py)                    │
│  ┌─────────────────────────────────────────────────────┐   │
│  │              MCP Tools Router                       │   │
│  │  • send_email                                       │   │
│  │  • receive_emails_imap                              │   │
│  │  • receive_emails_pop3                              │   │
│  └─────────────────┬───────────────────────────────────┘   │
└────────────────────┼───────────────────────────────────────┘
                     │
        ┌────────────┴────────────┐
        │                         │
┌───────▼────────┐      ┌────────▼────────┐
│  EmailSender   │      │ EmailReceiver   │
│   (SMTP)       │      │  (IMAP/POP3)    │
└───────┬────────┘      └────────┬────────┘
        │                        │
        │ ┌──────────────────────┴────┐
        │ │   Validators & Utils      │
        │ │  • Email validation       │
        │ │  • Normalization          │
        │ │  • Formatting             │
        │ └──────────────────────────┬┘
        │                            │
        └────────────────┬───────────┘
                         │
        ┌────────────────▼───────────────┐
        │      Email Service Providers    │
        │  • Gmail (SMTP/IMAP)           │
        │  • Outlook (SMTP/IMAP)         │
        │  • Yahoo (SMTP/IMAP)           │
        │  • Custom SMTP/IMAP Servers    │
        └────────────────────────────────┘

项目结构

email-send-mcp/
├── main.py                      # Entry point - initializes and runs FastMCP server
├── src/
│   ├── __init__.py             # Package initialization
│   ├── config.py               # Configuration management with Pydantic Settings
│   ├── server.py               # FastMCP server setup and MCP tools definition
│   ├── services/
│   │   ├── __init__.py
│   │   ├── email_sender.py     # SMTP email sending service
│   │   └── email_receiver.py   # IMAP/POP3 email receiving service
│   └── utils/
│       ├── __init__.py
│       └── validators.py        # Email validation and formatting utilities
├── tests/                       # Test suite
│   ├── __init__.py
│   ├── test_config.py          # Configuration tests
│   ├── test_validators.py      # Email validation tests
│   └── ...
├── logs/                        # Application logs (auto-created)
├── Dockerfile                   # Container configuration
├── docker-compose.yml          # Docker Compose setup (optional)
├── pyproject.toml              # Project dependencies and metadata
├── .env.example                # Example environment configuration
├── .env                        # Actual environment configuration (not in git)
├── README.md                   # This file
├── QUICKSTART.md              # Quick start guide
├── EMAIL_PROVIDERS.md         # Provider-specific configurations
├── CONTRIBUTING.md            # Contribution guidelines
├── LICENSE                    # MIT License
└── examples.py                # Usage examples

组件详细信息

1. main.py -应用程序入口点

  • 从加载环境变量 .env
  • 配置日志记录(控制台+文件)
  • 初始化FastMCP服务器
  • 设置SMTP、IMAP、POP3服务
  • 在端口8888上启动HTTP服务器

2. src/config.py -配置管理

  • 使用Pydantic设置进行类型安全配置
  • 从环境变量加载设置
  • 验证端口号和必填字段
  • 为设置访问提供单例模式
  • 支持多个电子邮件提供商

3. src/server.py -MCP服务器

  • 使用定义MCP工具 @mcp.tool() 装饰器
  • 集成EmailSender和EmailReceiver服务
  • 处理工具参数验证
  • 为AI助手格式化响应
  • 提供健康检查端点

4. src/services/email_sender.py -SMTP服务

  • 异步SMTP客户端使用 aiosmtplib
  • 支持TLS(端口587)和SSL(端口465)
  • 发送前验证所有电子邮件地址
  • 处理有大小限制的文件附件
  • 支持CC、BCC和HTML电子邮件
  • 智能MIME消息构造

5. src/services/email_receiver.py -IMAP/POP3服务

  • 异步IMAP客户端使用 aioimaplib
  • 使用同步POP3客户端 poplib
  • 文件夹/邮箱支持(IMAP)
  • 未读过滤(IMAP)
  • 具有适当编码处理的电子邮件解析
  • 附件元数据提取

6. src/utils/validators.py -电子邮件实用程序

  • 使用符合RFC的电子邮件验证 email-validator
  • 电子邮件规范化和格式化
  • 批量电子邮件验证
  • 显示名称格式

技术栈

组件 技术 目的
MCP框架 FastMCP 2.0 模型上下文协议服务器实现
SMTP客户端 aiosmtplib 异步SMTP电子邮件发送
IMAP客户端 aioimaplib 异步IMAP电子邮件接收
POP3客户端 poplib(stdlib) 同步POP3电子邮件接收
电子邮件验证 电子邮件验证器 符合RFC的电子邮件地址验证
设置管理 Pydantic设置 类型安全配置
环境变量 python dotenv .env文件支持
HTTP服务器 FastAPI(通过FastMCP) MCP的HTTP传输
包管理器 uv 快速Python包管理
测试 pytest,pytest-asyncio 测试框架
代码质量 黑色、isort、mypy、ruff 代码格式化和linting

数据流

发送电子邮件

1. MCP Client → send_email tool call
2. FastMCP Server → validates parameters
3. EmailSender → validates recipient addresses
4. EmailSender → constructs MIME message
5. EmailSender → connects to SMTP server (TLS/SSL)
6. EmailSender → authenticates with credentials
7. EmailSender → sends email
8. EmailSender → returns success/error status
9. FastMCP Server → formats response
10. Response → returns to MCP Client

接收电子邮件

1. MCP Client → receive_emails_imap tool call
2. FastMCP Server → validates parameters
3. EmailReceiver → connects to IMAP server (SSL)
4. EmailReceiver → authenticates with credentials
5. EmailReceiver → selects mailbox/folder
6. EmailReceiver → searches for emails (filtered)
7. EmailReceiver → fetches email messages
8. EmailReceiver → parses email content
9. EmailReceiver → extracts metadata and attachments
10. EmailReceiver → returns formatted email list
11. FastMCP Server → formats response
12. Response → returns to MCP Client

日志记录与监视

  • 日志位置: logs/email-send-mcp_YYYYMMDD.log
  • 日志轮换: 每日(午夜)
  • 日志格式: YYYY-MM-DD HH:MM:SS - logger_name - LEVEL - message
  • 日志级别: 调试、信息、警告、错误
  • 控制台输出: 促进发展
  • 结构化日志记录: 适用于云环境的JSON兼容格式

安全架构

  1. 凭证存储: 环境变量(从未硬编码)
  2. TLS/SSL: 对所有电子邮件连接强制执行
  3. 输入验证: 所有电子邮件在处理前都经过验证
  4. 附件验证: 文件大小和存在性检查
  5. 错误处理: 敏感数据未在错误中暴露
  6. 登录中: 从未记录的密码和秘密

🔧 故障排除

常见问题及解决方法

问题:“身份验证失败”或“凭据无效”

症状:

  • 错误消息:“535身份验证失败”或类似
  • 无法连接到SMTP/IMAP服务器

解决:

  1. 使用应用程序密码而不是常规密码

    • 对于Gmail: 创建应用程序密码
    • 雅虎:账户安全→ 生成应用程序密码
    • 对于Outlook:可能需要特定于应用程序的密码或OAuth
  2. 验证中的凭据 .env 文件

    # Check your .env file
    cat .env | grep -E "USERNAME|PASSWORD"
    
  3. 确保启用2FA (应用程序密码需要)

  4. 检查是否启用了IMAP/SMTP访问

    • Gmail:设置→ 查看所有设置→ 转发和POP/IMAP→ 启用IMAP
    • Outlook:设置→ 同步电子邮件→ POP和IMAP

问题:“连接超时”或“连接被拒绝”

症状:

  • 服务器没有响应
  • 60+秒后超时错误

解决:

  1. 检查防火墙设置

    # Test SMTP connectivity
    telnet smtp.gmail.com 587
    
    # Test IMAP connectivity
    telnet imap.gmail.com 993
    
  2. 验证服务器地址和端口

    • SMTP:通常端口587(TLS)或465(SSL)
    • IMAP:通常端口993(SSL)
    • POP3:通常端口995(SSL)
  3. 检查您的ISP是否阻止SMTP/IMAP端口

    • 一些ISP阻止端口25587
    • 尝试使用VPN或其他网络
  4. 验证TLS/SSL设置是否与您的提供商匹配

    # For port 587, use:
    SMTP_USE_TLS=true
    
    # For port 465, use:
    SMTP_USE_TLS=true  # aiosmtplib handles this automatically
    

问题:Gmail“应用访问不太安全”错误

症状:

  • “请通过您的网络浏览器登录”错误
  • 帐户访问被阻止

解决:

  1. 启用双因素身份验证

  2. 生成和使用应用程序密码

    • 访问 应用程序密码
    • 选择“邮件”和您的设备
    • 复制16个字符的密码
    • 使用于 .env 文件(删除空格)
  3. 永远不要使用“不太安全的应用程序访问” (已弃用且不安全)


问题:“找不到模块”错误

症状:

ModuleNotFoundError: No module named 'fastmcp'
ModuleNotFoundError: No module named 'dotenv'

解决:

# Reinstall dependencies
pip install -e .

# Or with uv
uv pip install -e .

# For development dependencies
pip install -e ".[dev]"

# Verify installation
python -c "import fastmcp; print('FastMCP OK')"
python -c "import dotenv; print('dotenv OK')"

问题:“权限被拒绝”或“找不到文件”(附件)

症状:

  • “找不到附件文件:/path/to/file.pdf”
  • 读取附件文件时出现权限错误

解决:

  1. 附件使用绝对路径

    # ✅ Good
    attachments=["/home/user/documents/report.pdf"]
    
    # ❌ Bad
    attachments=["report.pdf"]
    
  2. 验证文件是否存在并且可读

    ls -la /path/to/file.pdf
    # Should show readable permissions
    
  3. 检查文件大小

    # Default max is 25MB
    du -h /path/to/file.pdf
    

问题:“工具未出现在Claude Desktop中”

症状:

  • MCP服务器已配置,但工具未显示
  • Claude无法识别电子邮件命令

解决:

  1. 验证配置文件路径是否正确

    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • 窗户: %APPDATA%\Claude\claude_desktop_config.json
  2. 在配置中使用绝对路径

    {
      "mcpServers": {
        "email": {
          "command": "python",
          "args": ["/absolute/path/to/email-send-mcp/main.py"]
        }
      }
    }
    
  3. 完全重新启动克劳德桌面

    • 退出应用程序(不仅仅是关闭窗口)
    • 从应用程序/开始菜单重新启动
  4. 检查服务器日志

    # View logs to see if server started
    tail -f logs/email-send-mcp_*.log
    

问题:电子邮件已发送,但收件人未收到

症状:

  • “电子邮件已成功发送”消息
  • 但收件人从未收到过电子邮件

解决:

  1. 检查收件人的垃圾邮件文件夹

  2. 验证发件人电子邮件是否正确

    DEFAULT_FROM_EMAIL=your-actual-email@gmail.com
    
  3. 检查电子邮件提供商的已发送文件夹

  4. 验证收件人电子邮件地址是否有效

    # Test email validation
    from src.utils.validators import validate_email_address
    is_valid, result = validate_email_address("recipient@example.com")
    print(f"Valid: {is_valid}, Result: {result}")
    
  5. 检查是否有回复电子邮件 在您的收件箱中


问题:“超出最大附件大小”

症状:

  • 附件大小限制错误

解决:

  1. 检查文件大小

    du -h attachment.pdf
    
  2. 增加限制 .env

    MAX_ATTACHMENT_SIZE_MB=50  # Default is 25
    
  3. 压缩大文件 在连接之前

  4. 使用云存储链接 对于非常大的文件


问题:无法接收电子邮件/收件箱为空

症状:

  • “未找到电子邮件”消息
  • IMAP返回空结果

解决:

  1. 验证IMAP凭据是否正确

    IMAP_USERNAME=your-email@gmail.com
    IMAP_PASSWORD=your-app-password
    
  2. 检查邮箱名称是否正确

    # Common mailbox names
    receive_emails_imap(mailbox="INBOX")      # ✅
    receive_emails_imap(mailbox="Sent")       # ✅
    receive_emails_imap(mailbox="inbox")      # ❌ Case-sensitive
    
  3. 验证该文件夹中是否存在电子邮件

    • 通过web界面检查
    • 尝试不同的文件夹:“已发送”、“草稿”等。
  4. 增加限制参数

    receive_emails_imap(limit=50)  # Default is 10
    

调试提示

启用调试日志

添加 .env:

LOG_LEVEL=DEBUG
DEBUG=true

重新启动服务器并检查日志:

tail -f logs/email-send-mcp_$(date +%Y%m%d).log

手动测试SMTP连接

import asyncio
from src.services.email_sender import EmailSender

async def test():
    sender = EmailSender()
    result = await sender.send_email(
        recipient="test@example.com",
        subject="Test",
        body="Testing SMTP connection"
    )
    print(result)

asyncio.run(test())

手动测试IMAP连接

import asyncio
from src.services.email_receiver import EmailReceiver

async def test():
    receiver = EmailReceiver()
    result = await receiver.receive_emails_imap(limit=1)
    print(result)

asyncio.run(test())

检查环境变量

# Verify .env is being loaded
python -c "from src.config import get_settings; s = get_settings(); print(f'SMTP: {s.SMTP_SERVER}:{s.SMTP_PORT}')"

获取帮助

如果您仍然遇到问题:

  1. 检查现有问题: GitHub问题
  2. 搜索讨论: GitHub讨论
  3. 打开新问题:
    • 包括错误消息
    • 包括相关日志(删除敏感数据)
    • 包括您的配置(无密码)
    • 包括复制步骤

👥 贡献

我们欢迎捐款!以下是您可以提供帮助的方式:

贡献者快速入门

  1. 分叉并克隆存储库

    git clone https://github.com/YOUR_USERNAME/email-send-mcp.git
    cd email-send-mcp
    
  2. 安装开发依赖项

    pip install -e ".[dev]"
    
  3. 创建分支

    git checkout -b feature/your-feature-name
    
  4. 进行更改并添加测试

  5. 运行测试和梳理

    # Run tests
    pytest tests/ -v
    
    # Format code
    black src/ tests/ main.py
    isort src/ tests/ main.py
    
    # Type checking
    mypy src/
    
    # Linting
    ruff check src/ tests/
    
  6. 承诺并推动

    git commit -m "Add feature: description"
    git push origin feature/your-feature-name
    
  7. 创建拉取请求

贡献指南

  • 代码样式: 遵循PEP 8,使用黑色格式化程序
  • 测验: 为新功能添加测试
  • 文档: 更新README和文档字符串
  • 承诺: 写明确的提交消息
  • 问题: 将PR链接到相关问题

有关详细指南,请参阅 贡献.md.

📚 其他资源

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

🙏 致谢

  • FastMCP -优秀的MCP框架 @杰洛温
  • 人类 -模型上下文协议规范
  • 贡献者 -感谢所有贡献者!

📞 支持


⭐ 如果你觉得这个仓库有用,就把它标上!

由...制作❤️ 对于MCP社区