Content
# Email MCP Server
An email retrieval MCP (Model Context Protocol) server based on the FastMCP framework, supporting multi-email configuration, email retrieval, and attachment management features.
## Features
- 🔗 **MCP Protocol Support**: Based on the FastMCP framework, supports SSE and stdio transmission modes
- 📧 **Multiple Email Support**: Allows configuration of multiple email accounts without the need to input passwords during calls
- 📧 **Multi-Protocol Support**: Supports IMAP, POP3, and SMTP protocols, with IMAP/POP3 for receiving emails and SMTP for sending emails, automatically selecting the protocol based on configuration
- 📎 **Intelligent Attachment Management**: Organizes storage by email address and email UID, supporting isolation of attachments across multiple email accounts
- 🔄 **Intelligent Attachment Parsing**: Integrates MarkItDown to automatically parse various formats of attachments such as documents, spreadsheets, images, etc., supporting content extraction and Markdown conversion for formats like PDF, Word, Excel, CSV, PowerPoint, images, and more
- 📦 **Automatic Decompression**: Automatically detects and decompresses compressed files (ZIP, TAR, GZ, BZ2, XZ, etc.) in email attachments, supporting recursive extraction and intelligent renaming
- 🔍 **Flexible Querying**: Supports various filtering conditions such as time range, folder, and quantity limits
- 📊 **Standardized Output**: Unified JSON format response
- 🛡️ **Error Handling**: Comprehensive error handling and retry mechanisms
- 📝 **Detailed Logging**: Structured log recording for easier debugging and monitoring
## Install Dependencies
### Basic Dependencies
```bash
pip install -r requirements.txt
```
### Recommended Installation of MarkItDown (for Intelligent Attachment Parsing)
To achieve the best experience in attachment parsing, it is strongly recommended to install the Microsoft open-source tool MarkItDown:
```bash
# Install the Full-Featured Version (Recommended)
pip install 'markitdown[all]'
# Or install specific format support as needed
```bash
pip install 'markitdown[pdf,docx,xlsx,pptx]'
```
**MarkItDown Open Source Address**: https://github.com/microsoft/markitdown.git
> MarkItDown is an open-source document conversion tool by Microsoft that supports converting various formats such as PDF, Word, Excel, PowerPoint, and images to Markdown, making it ideal for integration with LLM (Large Language Model) applications.
## Configuration Settings
### 1. Environment Configuration
Copy the environment configuration file:
```bash
cp .env.example .env
```
Edit the `.env` file to set the email configuration file path:
```bash
EMAIL_CONFIG_FILE=email_accounts.json
```
### 2. Email Account Configuration
Copy the email configuration example file:
```bash
cp email_accounts.json.example email_accounts.json
```
Edit the `email_accounts.json` file to add your email accounts. IMAP, POP3, and SMTP protocols are supported:
#### IMAP Configuration Example (Recommended):
```json
{
"accounts": {
"user@gmail.com": {
"email_address": "user@gmail.com",
"password": "your_app_password",
"display_name": "Personal Gmail",
"protocol": "imap",
"imap_host": "imap.gmail.com",
"imap_port": 993,
"imap_use_ssl": true,
"smtp_host": "smtp.gmail.com",
"smtp_port": 587,
"smtp_use_tls": true,
"is_default": true
}
}
}
```
#### POP3 Configuration Example:
```json
{
"accounts": {
"user@outlook.com": {
"email_address": "user@outlook.com",
"password": "your_password",
"display_name": "Personal Outlook",
"protocol": "pop3",
"pop3_host": "outlook.office365.com",
"pop3_port": 995,
"pop3_use_ssl": true,
"smtp_host": "smtp-mail.outlook.com",
"smtp_port": 587,
"smtp_use_tls": true,
"is_default": false
}
}
}
```
#### SMTP Configuration Example (Send Emails Only):
```json
{
"accounts": {
"sender@gmail.com": {
"email_address": "sender@gmail.com",
"password": "your_gmail_app_password",
"display_name": "SMTP Only Sender",
"protocol": "smtp",
"smtp_host": "smtp.gmail.com",
"smtp_port": 587,
"smtp_use_tls": true,
"enabled": true
}
}
}
```
#### Hybrid Configuration Example:
```json
{
"accounts": {
"gmail@gmail.com": {
"email_address": "gmail@gmail.com",
"password": "gmail_app_password",
"display_name": "Gmail IMAP",
"protocol": "imap",
"imap_host": "imap.gmail.com",
"imap_port": 993,
"imap_use_ssl": true,
"smtp_host": "smtp.gmail.com",
"smtp_port": 587,
"smtp_use_tls": true,
"is_default": true
},
"legacy@company.com": {
"email_address": "legacy@company.com",
"password": "legacy_password",
"display_name": "Company POP3",
"protocol": "pop3",
"pop3_host": "mail.company.com",
"pop3_port": 995,
"pop3_use_ssl": true,
"smtp_host": "smtp.company.com",
"smtp_port": 587,
"smtp_use_tls": true,
"is_default": false
},
"sender@company.com": {
"email_address": "sender@company.com",
"password": "sender_password",
"display_name": "Company SMTP Sender",
"protocol": "smtp",
"smtp_host": "smtp.company.com",
"smtp_port": 587,
"smtp_use_tls": true,
"enabled": true
}
}
}
```
**Important Security Tips:**
- Add `email_accounts.json` to the `.gitignore` file
- For Gmail, use an app-specific password instead of the account password
- Ensure the configuration file permissions are set correctly (recommended 600)
### 3. Starting the Server
#### SSE Mode (Recommended)
```bash
python main.py -t sse --host localhost --port 8000
```
The server will start at `http://localhost:8000/sse`.
#### stdio Mode
```bash
python main.py -t stdio
```
## MCP Tool Description
### 1. fetch_emails
The main tool for retrieving the email list.
**Parameters:**
- `email_address` (required): The email address (must be configured in the configuration file)
- `folder` (optional): The email folder, default is "INBOX"
- `start_date` (optional): The start date, format "YYYY-MM-DD" or "YYYY-MM-DD HH:MM:SS"
- `end_date` (optional): The end date, same format as above
- `limit` (optional): The limit on the number of emails, default is 10, maximum is 1000
- `start_uid` (optional): The UID of the email to start fetching from
- `download_attachments` (optional): Whether to automatically download attachments, default is false
**Return Format:**
```json
{
"status": "success",
"total_emails": 5,
"emails": [
{
"uid": "12345",
"sender": "sender@example.com",
"recipients": ["recipient@example.com"],
"cc": [],
"bcc": [],
"subject": "Email Subject",
"content": "Email text content",
"html_content": "<html>Email HTML content</html>",
"date": "2024-01-01T10:00:00",
"attachments": [
{
"filename": "document.pdf",
"content_type": "application/pdf",
"size": 1024,
"local_path": "/path/to/attachments/12345/document.pdf",
"download_status": "success"
}
]
}
],
"timestamp": "2024-01-01T10:00:00"
}
```
### 2. get_attachment_info
Get the attachment information of the specified email.
**Parameters:**
- `email_address` (required): Email address
- `email_uid` (required): Email UID
### 3. read_attachment
Read the content of an attachment with intelligent parsing.
**Parameters:**
- `email_address` (required): Email address
- `email_uid` (required): Email UID
- `filename` (required): Attachment filename
- `parse_content` (optional): Whether to use MarkItDown to parse the content, default is true
### 4. list_attachments
List all attachments of the specified email, including the directory structure and extracted files.
**Parameters:**
- `email_address` (required): Email address
- `email_uid` (required): Email UID
**Return Format:**
```json
{
"status": "success",
"data": {
"email_uid": "12345",
"total_files": 5,
"total_directories": 2,
"files": [
{
"name": "document.pdf",
"path": "document.pdf",
"size": 1024,
"modified_time": "2024-01-01T10:00:00",
"is_archive": false,
"type": "file"
}
],
"directories": [
{
"name": "extracted_folder",
"path": "extracted_folder",
"type": "directory"
}
],
"structure_type": "hierarchical",
"extraction_info": {
"has_extractions": true,
"total_extracted": 3,
"extraction_time": "2024-01-01T10:00:00"
}
}
}
```
### 5. extract_archives
Manually trigger the extraction of the compressed files from the specified email.
**Parameters:**
- `email_address` (required): Email address
- `email_uid` (required): Email UID
**Return Format:**
```json
{
"status": "success",
"data": {
"total_extracted": 5,
"extracted_files": [
{
"archive": "archive.zip",
"extracted_to": "archive_extracted",
"files_count": 3
}
],
"extraction_time": "2024-01-01T10:00:00"
}
}
```
### 6. send_email
Send an email.
**Parameters:**
- `from_address` (required): Sender's email address (must be configured in the configuration file)
- `to_addresses` (required): Recipient's email addresses (comma-separated)
- `subject` (required): Email subject
- `body` (required): Email body (plain text)
- `cc_addresses` (optional): CC email addresses (comma-separated)
- `bcc_addresses` (optional): BCC email addresses (comma-separated)
- `html_body` (optional): HTML formatted email body
### 7. search_emails
Search for emails.
**Parameters:**
- `keywords` (required): Search keywords
- `search_type` (optional): Type of search (sender, recipient, cc, subject, content, attachment, all), default is "all"
- `page_size` (optional): Number of emails per page, default is 5
- `last_uid` (optional): The last email UID for pagination
### 8. get_storage_stats
Get attachment storage statistics.
### 9. cleanup_old_attachments
Clean up old attachments that are older than the specified number of days.
**Parameters:**
- `days`: The threshold in days, default is 30
## Supported Email Protocols and Servers
### Protocol Support
- **IMAP**: Supports complete email management features, including folder operations, email status synchronization, etc.
- **POP3**: Supports basic email retrieval functionality, suitable for email servers that do not support IMAP.
### Automatic Protocol Selection
The system will automatically select the use of IMAP or POP3 protocol based on the `protocol` field in the configuration file:
```json
{
"protocol": "imap", // or "pop3"
"imap_host": "imap.gmail.com",
"imap_port": 993,
"imap_use_ssl": true,
// POP3 configuration (used when protocol is "pop3")
"pop3_host": "pop.gmail.com",
"pop3_port": 995,
"pop3_use_ssl": true
}
```
### Common Email Service Provider Configuration
The server automatically recognizes the configuration of common email service providers:
**IMAP Configuration:**
- **Gmail**: imap.gmail.com:993
- **Outlook/Hotmail**: outlook.office365.com:993
- **Yahoo**: imap.mail.yahoo.com:993
- **iCloud**: imap.mail.me.com:993
- **Others**: Automatically attempts imap.{domain}:993
**POP3 Configuration:**
- **Gmail**: pop.gmail.com:995
- **Outlook/Hotmail**: outlook.office365.com:995
- **Yahoo**: pop.mail.yahoo.com:995
- **Others**: Automatically attempts pop.{domain}:995
## Attachment Storage Structure
```
attachments/
├── {email_uid_1}/
│ ├── attachment1.pdf
│ ├── attachment2.jpg
│ ├── archive.zip # Original compressed file (retained)
│ ├── archive_extracted/ # Extracted directory
│ │ ├── file1.txt
│ │ ├── file2.pdf
│ │ └── subfolder/
│ │ └── nested_file.doc
│ ├── attachments.json # Attachment metadata
│ └── extraction_log.json # Extraction log (if extraction operation occurred)
├── {email_uid_2}/
│ ├── document.docx
│ ├── data.tar.gz # Original compressed file
│ └── data_tar_gz_extracted/ # Extracted directory
│ ├── data.csv
│ └── readme.txt
└── ...
```
### Compressed File Handling Rules
1. **Automatic Extraction**: After the email attachment is downloaded, all supported compressed formats are automatically detected and extracted.
2. **Recursive Extraction**: If new compressed files are found after extraction, the process will continue until no compressed files are left.
3. **Intelligent Renaming**: If the extraction directory already exists, a numerical suffix will be automatically added (e.g., `archive_extracted_1`).
4. **Retain Original Files**: The original compressed files will not be deleted after extraction, facilitating future use.
5. **Supported Formats**: Common compressed formats such as ZIP, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, BZ2, XZ, etc.
## Configuration Options
### Command Line Parameters
```bash
python main.py --help
```
- `-t, --transport`: Transport mode (sse/stdio)
- `--host`: Host binding for SSE mode
- `--port`: Port binding for SSE mode
- `--log-level`: Log level
- `--attachments-dir`: Directory for storing attachments
## Security Considerations
1. **Password Security**: Email passwords are passed through parameters, please ensure they are used in a secure environment.
2. **Network Security**: SSL/TLS connections are used by default to connect to the mail server.
3. **File Security**: Attachment filenames will be sanitized to prevent path traversal attacks.
4. **Access Control**: It is recommended to run in a trusted network environment.
## Error Handling
The server provides detailed error information:
```json
{
"status": "error",
"error_type": "ConnectionError",
"error_message": "Failed to connect to email server",
"timestamp": "2024-01-01T10:00:00",
"request_id": "req_20240101_100000_123456"
}
```
## Development and Debugging
### Enable Debug Logging
```bash
python main.py --log-level DEBUG
```
### Project Structure
```
email_mcp_server/
├── src/
│ ├── __init__.py
│ ├── email_mcp.py # Main MCP Server
│ ├── email_client.py # Email Client
│ ├── attachment_manager.py # Attachment Management
│ └── utils.py # Utility Functions
├── memory-bank/ # Project Documentation
├── attachments/ # Attachment Storage
├── requirements.txt # Dependency List
├── main.py # Entry File
└── README.md # Documentation
```
## License
This project is licensed under the MIT License.
Connection Info
You Might Also Like
awesome-mcp-servers
A collection of MCP servers.
git
A Model Context Protocol server for Git automation and interaction.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
Appwrite
Build like a team of hundreds
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
oh-my-opencode
Background agents · Curated agents like oracle, librarians, frontend...