Email Processing MCP Server

Email Processing MCP Server

This is a complex task involving several steps and technologies. Here's a breakdown of the process and a conceptual outline of how you might implement it, along with considerations for each step: **1. Outlook Email Extraction and Date Filtering:** * **Technology:** Python with libraries like `win32com.client` (for Windows) or `imaplib` (cross-platform, but requires IMAP access enabled in Outlook). * **Process:** 1. **Connect to Outlook:** * **`win32com.client` (Windows):** This is the most direct way to access Outlook on Windows. ```python import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # 6 represents the Inbox messages = inbox.Items ``` * **`imaplib` (Cross-Platform):** Requires IMAP to be enabled in your Outlook account settings. This is more complex to set up but works on macOS and Linux. ```python import imaplib import email # Replace with your Outlook IMAP server and credentials imap_server = "outlook.office365.com" imap_user = "your_email@outlook.com" imap_password = "your_password" mail = imaplib.IMAP4_SSL(imap_server) mail.login(imap_user, imap_password) mail.select("inbox") result, data = mail.search(None, "ALL") # Or use specific search criteria for num in data[0].split(): result, data = mail.fetch(num, "(RFC822)") raw_email = data[0][1] email_message = email.message_from_bytes(raw_email) # Process email_message mail.close() mail.logout() ``` 2. **Date Filtering:** Iterate through the emails and check their sent/received dates. * **`win32com.client`:** ```python import datetime start_date = datetime.datetime(2023, 1, 1) # Example start date end_date = datetime.datetime(2023, 12, 31) # Example end date for message in messages: try: sent_date = message.SentOn.replace(tzinfo=None) # Remove timezone info for comparison if start_date <= sent_date <= end_date: # Process the email print(f"Subject: {message.Subject}, Sent: {sent_date}") except Exception as e: print(f"Error processing email: {e}") ``` * **`imaplib`:** You can use IMAP search criteria for date filtering *before* fetching the emails, which is more efficient. ```python from datetime import date, timedelta today = date.today() yesterday = today - timedelta(days=1) date_str = yesterday.strftime("%d-%b-%Y") # Format required by IMAP result, data = mail.search(None, f'SINCE "{date_str}"') # Search for emails since yesterday ``` 3. **Email Data Extraction:** Extract relevant information from each email: * Subject * Sender * Recipient(s) * Sent/Received Date * Body (plain text and/or HTML) * Attachments (optional) **2. SQLite Database Storage:** * **Technology:** Python's `sqlite3` library. * **Process:** 1. **Connect to SQLite:** ```python import sqlite3 conn = sqlite3.connect('emails.db') cursor = conn.cursor() ``` 2. **Create a Table:** ```python cursor.execute(''' CREATE TABLE IF NOT EXISTS emails ( id INTEGER PRIMARY KEY AUTOINCREMENT, subject TEXT, sender TEXT, recipient TEXT, sent_date DATETIME, body TEXT ) ''') conn.commit() ``` 3. **Insert Email Data:** ```python def insert_email(subject, sender, recipient, sent_date, body): cursor.execute(''' INSERT INTO emails (subject, sender, recipient, sent_date, body) VALUES (?, ?, ?, ?, ?) ''', (subject, sender, recipient, sent_date, body)) conn.commit() # Example usage: insert_email(message.Subject, message.SenderEmailAddress, message.To, message.SentOn, message.Body) ``` 4. **Close the Connection:** ```python conn.close() ``` **3. Vector Embedding Generation:** * **Technology:** A suitable embedding model (e.g., Sentence Transformers, OpenAI's embeddings API, Hugging Face Transformers) and a library to use it. * **Process:** 1. **Choose an Embedding Model:** * **Sentence Transformers:** Good for general-purpose semantic similarity. Easy to use and can run locally. ```python from sentence_transformers import SentenceTransformer model = SentenceTransformer('all-mpnet-base-v2') # Choose a model ``` * **OpenAI Embeddings API:** High-quality embeddings, but requires an OpenAI API key and incurs costs. ```python import openai openai.api_key = "YOUR_OPENAI_API_KEY" def get_embedding(text, model="text-embedding-ada-002"): text = text.replace("\n", " ") return openai.Embedding.create(input = [text], model=model)['data'][0]['embedding'] ``` * **Hugging Face Transformers:** Offers a wide range of models, but can be more complex to set up. 2. **Generate Embeddings:** Create embeddings for the email body (or subject + body). ```python # Using Sentence Transformers email_body = message.Body # Or message.HTMLBody, but clean it first embedding = model.encode(email_body) # Using OpenAI email_body = message.Body embedding = get_embedding(email_body) ``` **4. MongoDB Storage with Vector Search:** * **Technology:** MongoDB with Atlas Vector Search. * **Process:** 1. **Connect to MongoDB:** ```python from pymongo import MongoClient # Replace with your MongoDB connection string client = MongoClient("mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority") db = client["email_database"] collection = db["emails"] ``` 2. **Create a Vector Search Index (if it doesn't exist):** This is crucial for efficient vector search. You'll need to do this in the MongoDB Atlas UI or using the MongoDB shell. The index definition will depend on the embedding dimension of your chosen model. Example: ```javascript // MongoDB Shell db.emails.createIndex( { embedding: "vectorSearch", "indexConfig": { "dimensions": 768, // Replace with the dimension of your embedding model "similarity": "cosine", // Or "euclidean", "dotProduct" "vectorOptions": { "dataType": "float16", // Or "float32" "normalize": true } } }, { "name": "vectorSearchIndex" } ) ``` 3. **Store Email Data and Embeddings:** ```python def insert_email_mongo(subject, sender, recipient, sent_date, body, embedding): email_document = { "subject": subject, "sender": sender, "recipient": recipient, "sent_date": sent_date, "body": body, "embedding": embedding.tolist() # Convert NumPy array to list for MongoDB } collection.insert_one(email_document) # Example usage: insert_email_mongo(message.Subject, message.SenderEmailAddress, message.To, message.SentOn, message.Body, embedding) ``` **5. Semantic Search:** * **Process:** 1. **Get the Search Query:** The user enters a search query. 2. **Generate Embedding for the Query:** Use the *same* embedding model you used for the emails to generate an embedding for the search query. 3. **Perform Vector Search in MongoDB:** Use the `$vectorSearch` aggregation pipeline stage. ```python def search_emails(query, limit=10): query_embedding = model.encode(query).tolist() # Or get_embedding(query) if using OpenAI pipeline = [ { "$vectorSearch": { "index": "vectorSearchIndex", # The name of your vector search index "path": "embedding", "queryVector": query_embedding, "numCandidates": 100, # Adjust as needed "limit": limit } }, { "$project": { "_id": 0, "subject": 1, "body": 1, "score": { "$meta": "vectorSearchScore" } } } ] results = list(collection.aggregate(pipeline)) return results # Example usage: search_results = search_emails("meeting about project updates") for result in search_results: print(f"Subject: {result['subject']}, Score: {result['score']}") print(f"Body: {result['body'][:200]}...") # Print first 200 characters of the body ``` **Code Example (Illustrative - Requires Adaptation):** ```python import win32com.client import sqlite3 from sentence_transformers import SentenceTransformer from pymongo import MongoClient import datetime # --- Configuration --- SQLITE_DB_NAME = 'emails.db' MONGODB_CONNECTION_STRING = "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority" MONGODB_DATABASE_NAME = "email_database" MONGODB_COLLECTION_NAME = "emails" EMBEDDING_MODEL_NAME = 'all-mpnet-base-v2' # Or 'text-embedding-ada-002' if using OpenAI # --- Initialize Components --- outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items sqlite_conn = sqlite3.connect(SQLITE_DB_NAME) sqlite_cursor = sqlite_conn.cursor() model = SentenceTransformer(EMBEDDING_MODEL_NAME) # Or initialize OpenAI mongo_client = MongoClient(MONGODB_CONNECTION_STRING) mongo_db = mongo_client[MONGODB_DATABASE_NAME] mongo_collection = mongo_db[MONGODB_COLLECTION_NAME] # --- Database Setup --- sqlite_cursor.execute(''' CREATE TABLE IF NOT EXISTS emails ( id INTEGER PRIMARY KEY AUTOINCREMENT, subject TEXT, sender TEXT, recipient TEXT, sent_date DATETIME, body TEXT ) ''') sqlite_conn.commit() # --- Email Processing --- start_date = datetime.datetime(2023, 1, 1) end_date = datetime.datetime(2023, 12, 31) for message in messages: try: sent_date = message.SentOn.replace(tzinfo=None) if start_date <= sent_date <= end_date: subject = message.Subject sender = message.SenderEmailAddress recipient = message.To body = message.Body # 1. Store in SQLite sqlite_cursor.execute(''' INSERT INTO emails (subject, sender, recipient, sent_date, body) VALUES (?, ?, ?, ?, ?) ''', (subject, sender, recipient, sent_date, body)) sqlite_conn.commit() # 2. Generate Embedding embedding = model.encode(body) # Or use OpenAI # 3. Store in MongoDB email_document = { "subject": subject, "sender": sender, "recipient": recipient, "sent_date": sent_date, "body": body, "embedding": embedding.tolist() } mongo_collection.insert_one(email_document) print(f"Processed email: {subject}") except Exception as e: print(f"Error processing email: {e}") # --- Cleanup --- sqlite_conn.close() mongo_client.close() print("Email processing complete.") ``` **Key Considerations and Improvements:** * **Error Handling:** Robust error handling is crucial, especially when dealing with external APIs and data sources. Use `try...except` blocks extensively. * **Rate Limiting:** Be mindful of rate limits for the OpenAI API and other services. Implement delays or batch processing to avoid exceeding limits. * **Authentication:** Securely store and manage API keys and database credentials. Avoid hardcoding them directly in your script. Use environment variables or a configuration file. * **Data Cleaning:** Clean the email body before generating embeddings. Remove HTML tags, special characters, and irrelevant content. Consider using libraries like `BeautifulSoup` for HTML parsing. * **Scalability:** For large email datasets, consider using batch processing and asynchronous tasks to improve performance. Libraries like `Celery` or `Dask` can help. * **Incremental Updates:** Implement a mechanism to periodically check for new emails and update the databases and embeddings. You could use a scheduled task or a background process. * **Vector Search Index Optimization:** Experiment with different vector search index configurations (e.g., `numCandidates`, `similarity metric`) to optimize search performance. * **User Interface:** Create a user interface (e.g., using Flask, Django, or Streamlit) to allow users to enter search queries and view the results. * **Security:** If you're handling sensitive email data, implement appropriate security measures to protect the data at rest and in transit. * **Time Zones:** Pay close attention to time zones when filtering emails by date. Ensure that all dates are in the same time zone before comparing them. * **Attachment Handling:** If you need to process attachments, you'll need to extract them from the emails and store them separately. You could also generate embeddings for the attachment content. * **IMAP vs. Exchange Web Services (EWS):** For more advanced Outlook integration, consider using Exchange Web Services (EWS) instead of IMAP. EWS provides more features and better performance, but it's also more complex to set up. There are Python libraries like `exchangelib` that can help. This comprehensive outline should give you a solid foundation for building your email processing and semantic search application. Remember to adapt the code examples to your specific needs and environment. Good luck! **Simplified Chinese Translation of the Key Concepts:** Here's a translation of the key concepts into Simplified Chinese: * **Outlook Email Extraction:** Outlook 邮件提取 (Outlook yóujiàn tíqǔ) * **Date Filtering:** 日期过滤 (rìqí guòlǜ) * **SQLite Database:** SQLite 数据库 (SQLite shùjùkù) * **Vector Embeddings:** 向量嵌入 (xiàngliàng qiànrù) * **Semantic Search:** 语义搜索 (yǔyì sōusuǒ) * **MongoDB:** MongoDB * **Atlas Vector Search:** Atlas 向量搜索 (Atlas xiàngliàng sōusuǒ) * **Sentence Transformers:** 句子转换器 (jùzi zhuǎnhuànqì) * **OpenAI Embeddings API:** OpenAI 嵌入 API (OpenAI qiànrù API) * **Hugging Face Transformers:** Hugging Face 转换器 (Hugging Face zhuǎnhuànqì) * **Email Body:** 邮件正文 (yóujiàn zhèngwén) * **Search Query:** 搜索查询 (sōusuǒ cháxún) * **Aggregation Pipeline:** 聚合管道 (jùhé guǎndào) * **Index:** 索引 (suǒyǐn) * **Connection String:** 连接字符串 (liánjiē zìfúchuàn) * **Rate Limiting:** 速率限制 (sùlǜ xiànzhì) * **Data Cleaning:** 数据清洗 (shùjù qīngxǐ) * **Scalability:** 可扩展性 (kě kuòzhǎn xìng) * **Incremental Updates:** 增量更新 (zēngliàng gēngxīn) * **User Interface:** 用户界面 (yònghù jièmiàn) * **Security:** 安全性 (ānquán xìng) * **Time Zones:** 时区 (shíqū) * **Attachment Handling:** 附件处理 (fùjiàn chǔlǐ) * **Exchange Web Services (EWS):** Exchange Web 服务 (EWS)

Category
访问服务器

README

Email Processing MCP Server

此 MCP 服务器提供电子邮件处理功能,集成了 MongoDB 用于语义搜索,以及 SQLite 用于高效存储和检索。

功能

  • 处理来自 Outlook 的电子邮件,并支持按日期范围过滤
  • 将电子邮件存储在 SQLite 数据库中,并进行适当的连接管理
  • 使用 Ollama 生成向量嵌入
  • 支持多邮箱
  • 支持收件箱、已发送邮件和(可选)已删除邮件文件夹

即将推出的功能

  • 具有语义功能的电子邮件搜索
  • 使用 LLM 进行电子邮件摘要
  • 自动电子邮件分类
  • 可定制的电子邮件报告
  • 高级过滤选项
  • Outlook 草拟电子邮件回复
  • Outlook 规则建议
  • 扩展的数据库选项,集成 Neo4j 和 ChromaDB

前提条件

  • Python 3.10 或更高版本
  • Ollama 在本地运行(用于嵌入)
  • 已安装 Microsoft Outlook
  • Windows 操作系统(用于 Outlook 集成)
  • MongoDB 服务器(用于存储嵌入)

安装

  1. 安装 uv (如果尚未安装):
pip install uv
  1. 创建一个虚拟环境:
uv venv .venv
  1. 激活虚拟环境:

    Windows:

    .venv\Scripts\activate
    

    macOS/Linux:

    source .venv/bin/activate
    
  2. 安装依赖项:

uv pip install -e .
  1. 安装 fastmcp 包:
uv pip install fastmcp
  1. 确保 Ollama 在本地运行,并具有所需的模型:
ollama pull nomic-embed-text

配置

将服务器添加到您的 Claude for Desktop 配置文件中:

  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "outlook-email": {
      "command": "C:/Users/username/path/to/mcp-server-outlook-email/.venv/Scripts/python",
      "args": [
        "C:/Users/username/path/to/mcp-server-outlook-email/src/mcp_server.py"
      ],
      "env": {
        "MONGODB_URI": "mongodb://localhost:27017/MCP?authSource=admin",
        "SQLITE_DB_PATH": "C:\\Users\\username\\path\\to\\mcp-server-outlook-email\\data\\emails.db",
        "EMBEDDING_BASE_URL": "http://localhost:11434",
        "EMBEDDING_MODEL": "nomic-embed-text",
        "COLLECTION_NAME": "outlook-emails",
        "PROCESS_DELETED_ITEMS": "false"
      }
    }
  }
}

追踪和监控

该服务器旨在支持外部追踪和监控解决方案。 MCP 日志记录实现已被有意删除,以支持将单独实现的更强大的追踪方法。

注意:不要尝试重新实现以前的日志记录系统。 未来将提供新的追踪解决方案。

配置字段说明:

  • command: 虚拟环境中 Python 可执行文件的完整路径
  • args: 包含 MCP 服务器脚本完整路径的数组
  • env: 用于配置的环境变量
    • MONGODB_URI: MongoDB 连接字符串
    • SQLITE_DB_PATH: SQLite 数据库文件的绝对路径
    • EMBEDDING_BASE_URL: Ollama 服务器 URL
    • EMBEDDING_MODEL: 用于嵌入的模型
    • LLM_MODEL: 用于 LLM 操作的模型
    • COLLECTION_NAME: 要使用的 MongoDB 集合的名称(必需)
    • PROCESS_DELETED_ITEMS: 是否处理已删除邮件文件夹中的电子邮件(可选,默认值:“false”)
  • disabled: 服务器是否已禁用(应为 false)
  • alwaysAllow: 不需要用户确认的工具数组
  • autoApprove: 可以自动批准的工具数组

将路径替换为您系统上的实际路径。 请注意,env 部分中的 Windows 路径应使用双反斜杠。

可用工具

1. process_emails

处理指定日期范围内的电子邮件:

{
  "start_date": "2024-01-01",    # ISO 格式日期 (YYYY-MM-DD)
  "end_date": "2024-02-15",      # ISO 格式日期 (YYYY-MM-DD)
  "mailboxes": ["All"]           # 邮箱名称列表,或 ["All"] 表示所有邮箱
}

该工具将:

  1. 连接到指定的 Outlook 邮箱
  2. 检索来自收件箱和已发送邮件文件夹(以及已启用时的已删除邮件)的电子邮件
  3. 将电子邮件存储在 SQLite 数据库中
  4. 使用 Ollama 生成嵌入
  5. 将嵌入存储在 MongoDB 中以进行语义搜索

在 Claude 中的示例用法

"Process emails from February 1st to February 17th from all mailboxes"

架构

该服务器使用混合搜索方法:

  1. SQLite 数据库用于:

    • 主要电子邮件存储
    • 全文搜索功能
    • 处理状态跟踪
    • 高效过滤
    • 如果目录不存在,则自动创建
    • 正确关闭连接以防止数据库锁定
  2. MongoDB 用于:

    • 向量嵌入存储
    • 语义相似性搜索
    • 元数据过滤
    • 高效检索
    • 使用后正确关闭连接

错误处理

该服务器为常见问题提供详细的错误消息:

  • 无效的日期格式
  • 与 Outlook 的连接问题
  • MongoDB 错误
  • 使用重试逻辑的嵌入生成失败
  • SQLite 存储错误
  • Ollama 服务器连接问题,具有自动重试

资源管理

该服务器实现了适当的资源管理以防止问题:

  • 数据库连接(SQLite 和 MongoDB)在服务器的生命周期内保持打开状态,以防止“无法对已关闭的数据库进行操作”错误
  • 仅在服务器关闭时才关闭连接,使用 atexit 处理程序
  • 析构函数和上下文管理器用作后备,以确保在垃圾回收对象时关闭连接
  • 连接管理旨在平衡资源使用与运营可靠性
  • 针对 Ollama 等外部服务的强大重试逻辑,以处理临时连接问题

安全注意事项

  • 该服务器仅处理来自指定邮箱的电子邮件
  • 所有数据都存储在本地(SQLite)和 MongoDB 中
  • 除了本地 Ollama 服务器之外,没有外部 API 调用
  • 需要用户明确批准才能进行电子邮件处理
  • 没有通过 MCP 接口暴露敏感电子邮件数据

调试

如果您遇到问题:

  1. 验证电子邮件是否已成功处理(检查 process_emails 响应)
  2. 确保 Ollama 服务器正在运行以进行嵌入生成
  3. 检查 SQLite 数据库是否可访问
  4. 验证 MongoDB 连接是否正常工作

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选