mcp-imap
Allows email management via IMAP and SMTP protocols, supporting search, retrieval, sending, and organization of emails in Gmail.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-imapshow me unread emails in my inbox"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP IMAP E-mail Server
English
MCP (Model Context Protocol) server for email operations via IMAP and SMTP protocols. This server enables AI agents to interact with email accounts through a standardized interface. Yandex.Mail is default mail server.
Features
List mailboxes: Enumerate available email folders
Search emails: Find emails by various criteria (subject, sender, date, etc.)
Retrieve emails: Get full email content including body and attachments
Send emails: Compose and send email messages with optional attachments
Manage emails: Mark emails as read, delete emails
Related MCP server: MCP Email Server
Architecture
The MCP Email Server is built using the official MCP Python SDK and follows the Model Context Protocol specification. It communicates via JSON-RPC 2.0 over stdin/stdout, making it compatible with any MCP client.
Components
MCP Server (
src/mcp_server/server.py): Main server implementation using MCP SDKIMAP Tools (
src/mcp_server/tools/imap_tools.py): Email retrieval and management operationsSMTP Tools (
src/mcp_server/tools/smtp_tools.py): Email sending operationsConfiguration (
src/mcp_server/config/settings.py): Environment-based configuration managementError Handling (
src/mcp_server/errors.py): Custom error hierarchy with proper error codes
Connection Management
IMAPConnectionManager: Async context manager for IMAP connections with automatic cleanup
SMTPConnectionManager: Async context manager for SMTP connections with TLS/SSL support
Both managers handle authentication, connection errors, and timeouts automatically
Design Patterns
Async/Await: All I/O operations are asynchronous for better performance
Context Managers: Connection lifecycle management with automatic cleanup
Type Safety: Pydantic models for request/response validation
Structured Logging: JSON-formatted logs for better observability
Quick Start
Prerequisites
Docker installed and running
Email account credentials (username, password/app password)
IMAP/SMTP server information (defaults to Yandex Mail)
Installation
Create environment file (
.env):
# Required - Email account credentials
IMAP_USERNAME=your_email@yandex.ru
IMAP_PASSWORD=your_app_password
# Optional - Server configuration (defaults shown)
IMAP_HOST=imap.yandex.ru
IMAP_PORT=993
SMTP_HOST=smtp.yandex.ru
SMTP_PORT=465
SMTP_USE_TLS=true
# Optional - Logging
LOG_LEVEL=INFOSecurity Note: For Yandex Mail, use an application password instead of your main account password.
Build Docker image:
docker build -t mcp-email-server .Run container:
docker run --rm -i --env-file .env mcp-email-serverThe server communicates via JSON-RPC 2.0 over stdin/stdout (MCP protocol).
Using with MCP Clients
The MCP Email Server is compatible with any MCP client. Below are configuration examples for popular clients.
Claude Desktop
Locate Claude Desktop configuration file:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.json
Add MCP Email Server configuration:
{
"mcpServers": {
"email": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"/absolute/path/to/.env",
"mcp-email-server"
]
}
}
}Important: Use absolute path to your .env file. On Windows, use forward slashes or escaped backslashes:
Windows example:
"C:/Users/YourName/.env"or"C:\\\\Users\\\\YourName\\\\.env"
Restart Claude Desktop to load the new configuration.
Verify connection: Open Claude Desktop and check that the email server appears in the MCP servers list.
Cherry Studio
Open Cherry Studio Settings → MCP Servers
Add new server with the following configuration:
{
"name": "Email Server",
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"/absolute/path/to/.env",
"mcp-email-server"
]
}Save configuration and restart Cherry Studio.
Cline (VS Code Extension)
Install Cline extension in VS Code
Open VS Code settings (
.vscode/settings.jsonor User Settings)Add MCP server configuration:
{
"cline.mcpServers": {
"email": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"${workspaceFolder}/.env",
"mcp-email-server"
]
}
}
}MCP Inspector (Testing Tool)
MCP Inspector is a web-based tool for testing MCP servers:
Install MCP Inspector:
npm install -g @modelcontextprotocol/inspectorRun inspector:
mcp-inspector docker run --rm -i --env-file .env mcp-email-serverOpen browser to the URL shown in the terminal (usually
http://localhost:3000)
Custom Client Integration
For custom clients or direct integration, the server communicates via JSON-RPC 2.0 over stdin/stdout:
Connection Setup:
import subprocess
import json
# Start server process
process = subprocess.Popen(
["docker", "run", "--rm", "-i", "--env-file", ".env", "mcp-email-server"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True
)
# Step 1: Initialize
init_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "my-client", "version": "1.0.0"}
}
}
process.stdin.write(json.dumps(init_request) + "\n")
process.stdin.flush()
# Read initialize response
init_response = json.loads(process.stdout.readline())
print("Initialized:", init_response)
# Step 2: List available tools
tools_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}
process.stdin.write(json.dumps(tools_request) + "\n")
process.stdin.flush()
tools_response = json.loads(process.stdout.readline())
print("Available tools:", tools_response)
# Step 3: Call a tool
tool_request = {
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "list_mailboxes",
"arguments": {}
}
}
process.stdin.write(json.dumps(tool_request) + "\n")
process.stdin.flush()
tool_response = json.loads(process.stdout.readline())
print("Tool result:", tool_response)Troubleshooting Client Connections
Common Issues:
Server not appearing in client:
Verify Docker image is built:
docker images | grep mcp-email-serverCheck
.envfile path is absolute and correctVerify
.envfile has correct permissions (readable)
Authentication errors:
Ensure
.envfile contains valid credentialsFor Yandex Mail, use application password, not main password
Check IMAP/SMTP are enabled in your email account settings
Connection timeouts:
Verify IMAP_HOST and SMTP_HOST are correct
Check firewall settings allow outbound connections
Try increasing
CONNECTION_TIMEOUTin.env
Permission errors:
Ensure Docker has permission to read
.envfileOn Linux/macOS:
chmod 600 .env(restrict permissions for security)
Configuration
Environment Variables
Variable | Required | Default | Description |
| Yes | - | Email account username |
| Yes | - | Email account password (use app password) |
| No |
| IMAP server hostname |
| No |
| IMAP server port |
| No |
| SMTP server hostname |
| No |
| SMTP server port (465 for SSL, 587 for TLS) |
| No |
| Use TLS for SMTP |
| No |
| Logging level (DEBUG, INFO, WARN, ERROR) |
| No |
| Connection timeout in seconds |
Using Different Email Providers
Gmail
IMAP_HOST=imap.gmail.com
IMAP_PORT=993
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USE_TLS=trueOutlook/Office 365
IMAP_HOST=outlook.office365.com
IMAP_PORT=993
SMTP_HOST=smtp.office365.com
SMTP_PORT=587
SMTP_USE_TLS=trueMCP Tools
The server exposes the following MCP tools:
list_mailboxes: List all available mailboxes
search_emails: Search emails by various criteria
get_email: Retrieve full email with body and attachments
send_email: Send email messages
mark_email_read: Mark email as read
delete_email: Delete emails
See contracts/tools.md for detailed API documentation.
Additional Documentation
Architecture: docs/ARCHITECTURE.md - System architecture and design patterns
Testing: docs/TESTING.md - Test suite documentation and guidelines
Contributing: docs/CONTRIBUTING.md - Contribution guidelines and development setup
Development
Requirements
Python 3.11+
Docker (for containerization)
Local Development
Install dependencies:
pip install -r requirements.txtSet environment variables (see Configuration section)
Run server:
python -m mcp_server.serverTesting
The project includes a comprehensive test suite with unit and integration tests.
Running Tests
# Install test dependencies
pip install -e ".[dev]"
# Run all tests
pytest
# Run with coverage
pytest --cov=mcp_server --cov-report=html
# Run specific test file
pytest tests/unit/test_imap_tools.py
# Run with verbose output
pytest -vTest Structure
Unit Tests (
tests/unit/): Test individual components in isolationtest_server_sdk.py: MCP server teststest_imap_tools.py: IMAP operation teststest_smtp_tools.py: SMTP operation teststest_config.py: Configuration teststest_errors.py: Error handling tests
Integration Tests (
tests/integration/): Test end-to-end server functionalitytest_server_sdk_integration.py: Full server lifecycle tests
Fixtures (
tests/fixtures/): Reusable test data and mocksimap_responses.py: Mock IMAP responsessmtp_responses.py: Mock SMTP responsesemail_samples.py: Sample email data
Writing Tests
Tests use pytest with pytest-asyncio for async support. Mock IMAP/SMTP clients are provided via fixtures to avoid requiring actual email servers.
Example test:
@pytest.mark.asyncio
async def test_list_mailboxes(mock_config, mock_imap_client):
with patch("mcp_server.tools.imap_tools.aioimaplib.IMAP4_SSL", return_value=mock_imap_client):
with patch("mcp_server.tools.imap_tools.get_config", return_value=mock_config):
result = await list_mailboxes({})
assert "mailboxes" in resultSee tests/README.md for more details on writing tests.
Contributing
We welcome contributions! Please follow these guidelines:
Development Setup
Fork and clone the repository:
git clone https://github.com/your-username/mcp-imap.git
cd mcp-imapCreate a virtual environment:
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activateInstall dependencies:
pip install -e ".[dev]"Set up pre-commit hooks (optional):
pre-commit installCode Style
The project uses:
ruff: Linting and code formatting
black: Code formatting (via ruff)
mypy: Type checking
Run checks:
ruff check .
ruff format .
mypy src/Pull Request Process
Create a feature branch from
mainMake your changes with tests
Ensure all tests pass:
pytestRun code quality checks:
ruff check . && mypy src/Update documentation if needed
Submit a pull request with a clear description
Issue Reporting
When reporting issues, please include:
Description of the problem
Steps to reproduce
Expected vs actual behavior
Environment details (Python version, OS, email provider)
Relevant logs (with credentials redacted)
Troubleshooting
Common Issues
Authentication Failures
Symptoms: "Authentication failed" or "LOGIN failed" errors
Solutions:
Verify credentials are correct in
.envfileFor Yandex Mail: Use application password, not main password
For Gmail: Enable "App Passwords" in account settings
Check if 2FA requires app-specific password
Verify
IMAP_USERNAMEmatches email address exactly
Connection Timeouts
Symptoms: "Connection timeout" or "Connection failed" errors
Solutions:
Verify IMAP/SMTP host and port are correct for your provider
Check firewall allows outbound connections on ports 993 (IMAP), 465/587 (SMTP)
Try different port:
Port 465: SSL/TLS (use
SMTP_USE_TLS=true)Port 587: STARTTLS (use
SMTP_USE_TLS=true)
Increase timeout:
CONNECTION_TIMEOUT=60Check network connectivity:
telnet imap.yandex.ru 993
Email Not Sending
Symptoms: SMTP send operations fail
Solutions:
Verify SMTP credentials match IMAP credentials
Check port matches encryption:
Port 465: SSL (implicit TLS)
Port 587: STARTTLS (explicit TLS)
Ensure
SMTP_USE_TLSmatches port configurationCheck server logs for specific error messages
Verify sender address matches authenticated account
Email Not Found
Symptoms: "Email UID not found" errors
Solutions:
Verify UID is correct (UIDs are mailbox-specific)
Check mailbox name is correct (case-sensitive)
Email may have been moved or deleted
Try searching for email first to get current UID
Debug Logging
Enable detailed logging to troubleshoot issues:
LOG_LEVEL=DEBUGLogs are output in JSON format to stderr. Example log entry:
{
"host": "imap.yandex.ru",
"port": 993,
"event": "Connecting to IMAP server",
"timestamp": "2026-01-05T10:00:00Z",
"level": "info"
}Error Codes
The server uses structured error codes:
CONNECTION_ERROR: Network or connection issuesAUTHENTICATION_ERROR: Login/authentication failuresNOT_FOUND_ERROR: Resource not found (email, mailbox)VALIDATION_ERROR: Invalid input parametersTIMEOUT_ERROR: Operation timeoutSERVER_ERROR: Internal server error
See src/mcp_server/errors.py for complete error definitions.
API Reference
⚠️ Important: Request Format and Initialization
The server uses newline-delimited JSON format. Each JSON-RPC request must be sent as a single line terminated with a newline character. Sending JSON across multiple lines will cause parse errors.
⚠️ CRITICAL: You must initialize the server before calling tools!
According to the MCP protocol, you must first send an initialize request, wait for the response, and only then call tools. The server will reject tool calls sent before initialization.
Step 1: Initialize the server
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test-client", "version": "1.0.0"}}}Step 2: After receiving initialize response, call tools
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_mailboxes", "arguments": {}}}Complete example using echo:
# Initialize
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test-client", "version": "1.0.0"}}}' | docker run --rm -i --env-file .env mcp-email-server
# Then call tool (after initialization completes)
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_mailboxes", "arguments": {}}}' | docker run --rm -i --env-file .env mcp-email-serverComplete example using Python:
import json
import subprocess
# Start server process
process = subprocess.Popen(
["docker", "run", "--rm", "-i", "--env-file", ".env", "mcp-email-server"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True
)
# Step 1: Initialize
init_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "test-client", "version": "1.0.0"}
}
}
process.stdin.write(json.dumps(init_request) + "\n")
process.stdin.flush()
# Read initialize response
init_response = process.stdout.readline()
print("Initialize response:", json.loads(init_response))
# Step 2: Call tool (after initialization)
tool_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "list_mailboxes",
"arguments": {}
}
}
process.stdin.write(json.dumps(tool_request) + "\n")
process.stdin.flush()
# Read tool response
tool_response = process.stdout.readline()
print("Tool response:", json.loads(tool_response))Incorrect format (multiple lines - will cause parse errors):
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_mailboxes",
"arguments": {}
}
}Tools Overview
Tool | Description | Parameters |
| List all mailboxes | None |
| Search emails by criteria | mailbox, subject, from, to, date_from, date_to, unread_only, has_attachments, limit |
| Retrieve full email | uid, mailbox, include_attachments |
| Send email message | to, subject, body_text, body_html, cc, bcc, attachments, reply_to |
| Mark email as read | uid, mailbox |
| Delete email | uid, mailbox, permanent |
Detailed Documentation
Tool Contracts: specs/001-mcp-email-server/contracts/tools.md
Data Models: specs/001-mcp-email-server/data-model.md
Quickstart Guide: specs/001-mcp-email-server/quickstart.md
Example Use Cases
Use Case 1: Monitor Unread Emails
# 1. List mailboxes
mailboxes = await list_mailboxes({})
# 2. Search for unread emails in INBOX
unread = await search_emails({
"mailbox": "INBOX",
"unread_only": True,
"limit": 10
})
# 3. Get full content of first unread email
if unread["emails"]:
email = await get_email({
"uid": unread["emails"][0]["uid"],
"mailbox": "INBOX"
})Use Case 2: Send Automated Response
# 1. Get email to respond to
email = await get_email({"uid": "12345", "mailbox": "INBOX"})
# 2. Send reply
await send_email({
"to": [email["email"]["from"]],
"subject": f"Re: {email['email']['subject']}",
"body_text": "Thank you for your email. This is an automated response.",
"reply_to": email["email"]["message_id"]
})
# 3. Mark original as read
await mark_email_read({"uid": "12345", "mailbox": "INBOX"})Security
Best Practices
Use Application Passwords: Never use your main account password
Yandex Mail: Create app password
Gmail: Enable "App Passwords" in Google Account settings
Outlook: Use app-specific passwords for 2FA accounts
Secure Environment Files: Protect
.envfileschmod 600 .env # Restrict file permissionsDocker Secrets: For production, use Docker secrets instead of
.envfilesdocker secret create imap_password .envTLS/SSL Only: Never disable TLS in production
IMAP: Always use port 993 (SSL)
SMTP: Use port 465 (SSL) or 587 (STARTTLS)
Network Isolation: Run containers in isolated networks
docker network create mcp-network docker run --network mcp-network ...Credential Management:
Never commit
.envfiles to version controlUse secret management services in production (AWS Secrets Manager, HashiCorp Vault)
Rotate passwords regularly
Logging: Credentials are never logged
Password fields are redacted in logs
Enable DEBUG logging only in development
Input Validation: All inputs are validated using Pydantic schemas
Email addresses are validated
UIDs are validated
File sizes are limited
Security Features
✅ TLS/SSL connections mandatory
✅ Credential validation
✅ Input sanitization
✅ Error message sanitization (no credential leakage)
✅ Structured logging (no credential exposure)
✅ Connection timeout protection
✅ Rate limiting via connection management
License
MIT
Русский
MCP (Model Context Protocol) сервер для работы с электронной почтой через протоколы IMAP и SMTP. Этот сервер позволяет AI-агентам взаимодействовать с почтовыми аккаунтами через стандартизированный интерфейс. По умолчанию используются сервера Яндекс.Почта.
Возможности
Список почтовых ящиков: Перечисление доступных папок электронной почты
Поиск писем: Поиск писем по различным критериям (тема, отправитель, дата и т.д.)
Получение писем: Получение полного содержимого письма включая тело и вложения
Отправка писем: Составление и отправка писем с опциональными вложениями
Управление письмами: Отметка писем как прочитанных, удаление писем
Быстрый старт
Требования
Установленный и запущенный Docker
Учетные данные почтового аккаунта (имя пользователя, пароль/пароль приложения)
Информация о серверах IMAP/SMTP (по умолчанию Яндекс.Почта)
Установка
Создайте файл окружения (
.env):
# Обязательно - Учетные данные почтового аккаунта
IMAP_USERNAME=ваш_email@yandex.ru
IMAP_PASSWORD=ваш_пароль_приложения
# Опционально - Конфигурация сервера (показаны значения по умолчанию)
IMAP_HOST=imap.yandex.ru
IMAP_PORT=993
SMTP_HOST=smtp.yandex.ru
SMTP_PORT=465
SMTP_USE_TLS=true
# Опционально - Логирование
LOG_LEVEL=INFOПримечание по безопасности: Для Яндекс.Почты используйте пароль приложения вместо основного пароля аккаунта.
Соберите Docker образ:
docker build -t mcp-email-server .Запустите контейнер:
docker run --rm -i --env-file .env mcp-email-serverСервер общается через JSON-RPC 2.0 по stdin/stdout (протокол MCP).
Использование с MCP клиентами
MCP Email Server совместим с любыми MCP клиентами. Ниже приведены примеры конфигурации для популярных клиентов.
Claude Desktop
Найдите файл конфигурации Claude Desktop:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.json
Добавьте конфигурацию MCP Email Server:
{
"mcpServers": {
"email": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"/абсолютный/путь/к/.env",
"mcp-email-server"
]
}
}
}Важно: Используйте абсолютный путь к файлу .env. В Windows используйте прямые слеши или экранированные обратные слеши:
Пример для Windows:
"C:/Users/ВашеИмя/.env"или"C:\\\\Users\\\\ВашеИмя\\\\.env"
Перезапустите Claude Desktop для загрузки новой конфигурации.
Проверьте подключение: Откройте Claude Desktop и убедитесь, что email сервер появился в списке MCP серверов.
Cherry Studio
Откройте настройки Cherry Studio → MCP Servers
Добавьте новый сервер со следующей конфигурацией:
{
"name": "Email Server",
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"/абсолютный/путь/к/.env",
"mcp-email-server"
]
}Сохраните конфигурацию и перезапустите Cherry Studio.
Cline (Расширение VS Code)
Установите расширение Cline в VS Code
Откройте настройки VS Code (
.vscode/settings.jsonили Пользовательские настройки)Добавьте конфигурацию MCP сервера:
{
"cline.mcpServers": {
"email": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"${workspaceFolder}/.env",
"mcp-email-server"
]
}
}
}MCP Inspector (Инструмент для тестирования)
MCP Inspector — это веб-инструмент для тестирования MCP серверов:
Установите MCP Inspector:
npm install -g @modelcontextprotocol/inspectorЗапустите inspector:
mcp-inspector docker run --rm -i --env-file .env mcp-email-serverОткройте браузер по адресу, показанному в терминале (обычно
http://localhost:3000)
Интеграция с пользовательскими клиентами
Для пользовательских клиентов или прямой интеграции сервер общается через JSON-RPC 2.0 по stdin/stdout:
Настройка подключения:
import subprocess
import json
# Запуск процесса сервера
process = subprocess.Popen(
["docker", "run", "--rm", "-i", "--env-file", ".env", "mcp-email-server"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True
)
# Шаг 1: Инициализация
init_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "my-client", "version": "1.0.0"}
}
}
process.stdin.write(json.dumps(init_request) + "\n")
process.stdin.flush()
# Чтение ответа на инициализацию
init_response = json.loads(process.stdout.readline())
print("Инициализирован:", init_response)
# Шаг 2: Список доступных инструментов
tools_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}
process.stdin.write(json.dumps(tools_request) + "\n")
process.stdin.flush()
tools_response = json.loads(process.stdout.readline())
print("Доступные инструменты:", tools_response)
# Шаг 3: Вызов инструмента
tool_request = {
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "list_mailboxes",
"arguments": {}
}
}
process.stdin.write(json.dumps(tool_request) + "\n")
process.stdin.flush()
tool_response = json.loads(process.stdout.readline())
print("Результат инструмента:", tool_response)Устранение проблем с подключением клиентов
Частые проблемы:
Сервер не появляется в клиенте:
Проверьте, что Docker образ собран:
docker images | grep mcp-email-serverПроверьте, что путь к файлу
.envабсолютный и правильныйУбедитесь, что файл
.envимеет правильные права доступа (читаемый)
Ошибки аутентификации:
Убедитесь, что файл
.envсодержит корректные учетные данныеДля Яндекс.Почты используйте пароль приложения, а не основной пароль
Проверьте, что IMAP/SMTP включены в настройках вашего почтового аккаунта
Таймауты подключения:
Проверьте, что IMAP_HOST и SMTP_HOST указаны правильно
Проверьте настройки файрвола, разрешающие исходящие подключения
Попробуйте увеличить
CONNECTION_TIMEOUTв.env
Ошибки прав доступа:
Убедитесь, что Docker имеет права на чтение файла
.envВ Linux/macOS:
chmod 600 .env(ограничить права доступа для безопасности)
Конфигурация
Переменные окружения
Переменная | Обязательна | По умолчанию | Описание |
| Да | - | Имя пользователя почтового аккаунта |
| Да | - | Пароль почтового аккаунта (используйте пароль приложения) |
| Нет |
| Имя хоста IMAP сервера |
| Нет |
| Порт IMAP сервера |
| Нет |
| Имя хоста SMTP сервера |
| Нет |
| Порт SMTP сервера (465 для SSL, 587 для TLS) |
| Нет |
| Использовать TLS для SMTP |
| Нет |
| Уровень логирования (DEBUG, INFO, WARN, ERROR) |
| Нет |
| Таймаут подключения в секундах |
Использование различных почтовых провайдеров
Gmail
IMAP_HOST=imap.gmail.com
IMAP_PORT=993
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USE_TLS=trueOutlook/Office 365
IMAP_HOST=outlook.office365.com
IMAP_PORT=993
SMTP_HOST=smtp.office365.com
SMTP_PORT=587
SMTP_USE_TLS=trueMCP Инструменты
Сервер предоставляет следующие MCP инструменты:
list_mailboxes: Список всех доступных почтовых ящиков
search_emails: Поиск писем по различным критериям
get_email: Получение полного письма с телом и вложениями
send_email: Отправка писем
mark_email_read: Отметка письма как прочитанного
delete_email: Удаление писем
Подробная документация API доступна в contracts/tools.md.
Примеры запросов
⚠️ Важно: Инициализация сервера
Перед вызовом инструментов необходимо выполнить инициализацию сервера!
Согласно протоколу MCP, сначала нужно отправить запрос initialize, дождаться ответа, и только после этого вызывать инструменты. Сервер отклонит вызовы инструментов, отправленные до инициализации.
Шаг 1: Инициализация сервера
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test-client", "version": "1.0.0"}}}Шаг 2: После получения ответа на initialize, вызывайте инструменты
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_mailboxes", "arguments": {}}}Полный пример с использованием echo:
# Инициализация
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test-client", "version": "1.0.0"}}}' | docker run --rm -i --env-file .env mcp-email-server
# Затем вызов инструмента (после завершения инициализации)
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_mailboxes", "arguments": {}}}' | docker run --rm -i --env-file .env mcp-email-serverПолный пример с использованием Python:
import json
import subprocess
# Запуск процесса сервера
process = subprocess.Popen(
["docker", "run", "--rm", "-i", "--env-file", ".env", "mcp-email-server"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True
)
# Шаг 1: Инициализация
init_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "test-client", "version": "1.0.0"}
}
}
process.stdin.write(json.dumps(init_request) + "\n")
process.stdin.flush()
# Чтение ответа на инициализацию
init_response = process.stdout.readline()
print("Ответ на инициализацию:", json.loads(init_response))
# Шаг 2: Вызов инструмента (после инициализации)
tool_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "list_mailboxes",
"arguments": {}
}
}
process.stdin.write(json.dumps(tool_request) + "\n")
process.stdin.flush()
# Чтение ответа на вызов инструмента
tool_response = process.stdout.readline()
print("Ответ инструмента:", json.loads(tool_response))1. Список почтовых ящиков
Запрос (после инициализации):
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "list_mailboxes",
"arguments": {}
}
}Ответ:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"mailboxes": [
{
"name": "INBOX",
"message_count": 42,
"unread_count": 5
},
{
"name": "Sent",
"message_count": 123,
"unread_count": 0
}
]
}
}2. Поиск писем
Запрос:
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "search_emails",
"arguments": {
"mailbox": "INBOX",
"subject": "важно",
"unread_only": true,
"limit": 10
}
}
}Ответ:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"emails": [
{
"uid": "12345",
"subject": "Важное обновление",
"from": "sender@example.com",
"date": "2026-01-04T10:30:00Z",
"flags": []
}
],
"total_count": 3,
"returned_count": 3
}
}3. Получение письма
Запрос:
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_email",
"arguments": {
"uid": "12345",
"mailbox": "INBOX",
"include_attachments": true
}
}
}Ответ:
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"email": {
"uid": "12345",
"subject": "Важное обновление",
"from": "sender@example.com",
"to": ["you@yandex.ru"],
"date": "2026-01-04T10:30:00Z",
"body_text": "Содержимое письма...",
"body_html": "<p>Содержимое письма...</p>",
"attachments": [],
"flags": []
}
}
}4. Отправка письма
Запрос:
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "send_email",
"arguments": {
"to": ["recipient@example.com"],
"subject": "Тестовое письмо",
"body_text": "Это тестовое письмо, отправленное через MCP сервер.",
"body_html": "<p>Это тестовое письмо, отправленное через MCP сервер.</p>"
}
}
}Ответ:
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"message_id": "<unique-message-id@server>",
"sent_at": "2026-01-04T11:00:00Z"
}
}5. Отметка письма как прочитанного
Запрос:
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "mark_email_read",
"arguments": {
"uid": "12345",
"mailbox": "INBOX"
}
}
}Ответ:
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"success": true,
"uid": "12345"
}
}6. Удаление письма
Запрос:
{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "delete_email",
"arguments": {
"uid": "12345",
"mailbox": "INBOX",
"permanent": false
}
}
}Ответ:
{
"jsonrpc": "2.0",
"id": 6,
"result": {
"success": true,
"uid": "12345"
}
}Разработка
Требования
Python 3.11+
Docker (для контейнеризации)
Локальная разработка
Установите зависимости:
pip install -r requirements.txtУстановите переменные окружения (см. раздел Конфигурация)
Запустите сервер:
python -m mcp_server.serverТестирование
pytestБезопасность
Все учетные данные предоставляются через переменные окружения (никогда не захардкожены)
Подключения TLS/SSL обязательны для IMAP и SMTP
Пароли приложений рекомендуются для почтовых провайдеров
Учетные данные не логируются в открытом виде
Лицензия
MIT
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/andrewmalov/mcp-imap'
If you have feedback or need assistance with the MCP directory API, please join our Discord server