Skip to main content
Glama
pzanna

Email MCP Server

by pzanna

이메일 MCP 서버

IMAP 및 SMTP를 통해 이메일 액세스를 제공하는 모델 컨텍스트 프로토콜(MCP) 서버입니다. AI 에이전트와 애플리케이션이 표준화된 HTTP/SSE 인터페이스를 통해 이메일을 읽고, 검색하고, 보내고, 관리할 수 있도록 지원합니다.

주요 기능

  • 9가지 이메일 도구 (MCP 제공):

    • list_folders - 모든 IMAP 메일함/폴더 나열

    • search_emails - 필터(발신자, 제목, 날짜 범위, 읽음/플래그 상태)를 사용하여 이메일 검색

    • read_email - 본문 및 첨부 파일 메타데이터를 포함한 전체 이메일 내용 가져오기

    • mark_email - 이메일을 읽음/안 읽음 또는 플래그 설정/해제 상태로 표시

    • move_email - 폴더 간 이메일 이동

    • send_email - 새 이메일 발송 (일반 텍스트 또는 멀티파트 HTML)

    • reply_email - 스레드 헤더를 유지하며 이메일에 답장

    • download_attachment - 이메일 첨부 파일을 작업 공간 디렉터리로 다운로드

    • send_email_with_attachments - 작업 공간의 파일을 첨부하여 이메일 발송

  • 운영 환경 준비 완료 아키텍처:

    • 연결 풀링을 지원하는 비동기 네이티브 IMAP/SMTP

    • Pydantic 기반 구성 및 유효성 검사

    • 구조화된 예외 처리를 통한 포괄적인 오류 처리

    • X-API-Key 헤더를 통한 API 키 인증

    • Ubuntu 배포를 위한 systemd 서비스 파일 제공

  • 테스트 주도 개발(TDD):

    • 85개 이상의 단위 및 통합 테스트

    • 핵심 기능 100% 커버리지

    • 재현 가능한 테스트를 위한 모의(Mock) 이메일 서버

Claude Desktop에 설치 (권장)

이 서버를 사용하는 가장 쉬운 방법은 Claude Desktop용 단일 파일 설치 번들인 MCPB를 사용하는 것입니다.

1. 다운로드

최신 릴리스에서 email_mcp.mcpb를 다운로드하세요.

2. 설치

email_mcp.mcpb를 더블 클릭합니다. Claude Desktop이 설치 대화 상자를 엽니다.

3. 구성

메시지가 표시되면 메일 서버 자격 증명을 입력하세요. 모든 값은 OS 키체인(macOS 키체인 / Linux Secret Service)에 저장됩니다:

필드

설명

예시

IMAP Host

IMAP 서버 호스트 이름

imap.gmail.com

IMAP Port

IMAP 서버 포트

993 (SSL) · 143 (STARTTLS)

IMAP Username

이메일 주소

you@example.com

IMAP Password

비밀번호 또는 앱 전용 비밀번호

xxxx xxxx xxxx xxxx

IMAP SSL

IMAP에 SSL/TLS 사용

true (포트 993) · false (포트 143)

SMTP Host

SMTP 서버 호스트 이름

smtp.gmail.com

SMTP Port

SMTP 서버 포트

587 (STARTTLS) · 465 (SSL)

SMTP Username

이메일 주소

you@example.com

SMTP Password

비밀번호 또는 앱 전용 비밀번호

xxxx xxxx xxxx xxxx

SMTP STARTTLS

STARTTLS 모드

true (포트 587) · false · none (자동)

Gmail 사용자: 일반 Google 계정 비밀번호가 아닌 앱 비밀번호를 사용해야 합니다. Gmail 설정 → 전달 및 POP/IMAP에서 IMAP을 활성화하세요.

4. 사용

설치가 완료되면 Claude가 이메일에 액세스할 수 있습니다. 다음을 시도해 보세요:

"이번 주에 온 읽지 않은 이메일 나열해 줘" "alice@example.com이 보낸 프로젝트 관련 이메일 검색해 줘" "bob@example.com에게 제목 'Hello', 본문 'Hi Bob!'으로 이메일 보내줘" "이메일 UID 12345의 첫 번째 첨부 파일 다운로드해 줘" "report.pdf 파일을 team@example.com으로 보내줘"


요구 사항

  • Python 3.10+ (3.13 권장)

  • IMAP 및 SMTP 서버 액세스 권한

  • MCP 인증을 위한 API 키

빠른 시작

1. 복제 및 설정

git clone https://github.com/pzanna/email_mcp.git
cd email_mcp
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -r requirements.txt

2. 환경 구성

cp .env.example .env
# Edit .env with your credentials

필수 환경 변수:

# IMAP Configuration
IMAP_HOST=imap.gmail.com
IMAP_PORT=993
IMAP_USER=you@gmail.com
IMAP_PASSWORD=your-app-password
IMAP_SSL=true

# SMTP Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=you@gmail.com
SMTP_PASSWORD=your-app-password
# SMTP_STARTTLS mode: "none" (auto), "true" (force), "false" (disable)
SMTP_STARTTLS=true

# MCP Server Configuration
MCP_API_KEY=your-secret-api-key-here
MCP_HOST=127.0.0.1
MCP_PORT=8420
MCP_SERVER_NAME=email-mcp
MCP_BASE_URL=http://localhost:8420

# Optional
DEFAULT_FROM_NAME=Your Name
MAX_SEARCH_RESULTS=50
IMAP_POOL_SIZE=3

# Attachment Configuration
EMAIL_BASE_DIR=/path/to/workspace
MAX_ATTACHMENT_SIZE_MB=50

3. 서버 실행

로컬 개발 (Mac/Linux):

source .venv/bin/activate
uvicorn main:app --host 127.0.0.1 --port 8420

서버 액세스:

  • MCP 엔드포인트: http://localhost:8420/mcp

  • 상태 확인: http://localhost:8420/health

  • API 문서: http://localhost:8420/docs

테스트

# Run all tests
pytest tests/ -v

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

# Run specific test file
pytest tests/test_integration.py -v

# Run specific test
pytest tests/test_send.py::test_send_email_plain_text -v

85개 이상의 모든 테스트가 통과되어야 합니다.

사용 예시

인증

모든 MCP 엔드포인트는 X-API-Key 헤더가 필요합니다:

curl -H "X-API-Key: your-secret-api-key-here" \
  http://localhost:8420/mcp/tools

사용 가능한 도구 나열

curl -X GET http://localhost:8420/mcp/tools \
  -H "X-API-Key: your-secret-api-key-here"

이메일 검색

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "search_emails",
      "arguments": {
        "from": "user@example.com",
        "subject": "invoice",
        "since": "2024-01-01",
        "limit": 10
      }
    }
  }'

이메일 발송

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "send_email",
      "arguments": {
        "to": ["recipient@example.com"],
        "subject": "Test Email",
        "body": "This is a test email.",
        "from_name": "My Name"
      }
    }
  }'

이메일 읽기

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "read_email",
      "arguments": {
        "uid": "12345",
        "folder": "INBOX"
      }
    }
  }'

이메일 첨부 파일 다운로드

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "download_attachment",
      "arguments": {
        "uid": "12345",
        "attachment_index": 0,
        "folder": "INBOX",
        "filename_override": "renamed_file.pdf"
      }
    }
  }'

파일이 기본 디렉터리 내에 유지되도록 보안 검증을 거쳐 EMAIL_BASE_DIR/attachments/email/downloads/로 첨부 파일을 다운로드합니다.

첨부 파일과 함께 이메일 발송

curl -X POST http://localhost:8420/mcp/call \
  -H "X-API-Key: your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "send_email_with_attachments",
      "arguments": {
        "to": ["recipient@example.com"],
        "cc": ["manager@example.com"],
        "subject": "Monthly Report",
        "body": "Please find the reports attached.",
        "body_html": "<p>Please find the <strong>reports</strong> attached.</p>",
        "from_name": "John Doe",
        "attachment_paths": [
          "attachments/email/uploads/report1.pdf",
          "attachments/email/uploads/report2.xlsx"
        ]
      }
    }
  }'

완벽한 보안 검증 및 크기 제한 적용을 통해 작업 공간 디렉터리의 파일을 첨부합니다.

첨부 파일 처리

이메일 MCP 서버는 작업 공간 기반 파일 관리를 통해 안전한 첨부 파일 처리를 제공합니다.

작업 공간 디렉터리 구조

모든 첨부 파일 작업은 구성된 작업 공간 디렉터리로 제한됩니다:

EMAIL_BASE_DIR/
└── attachments/
    └── email/
        ├── downloads/    # Downloaded email attachments
        └── uploads/      # Files ready to attach to outgoing emails

보안 기능

  • 작업 공간 제한: 모든 파일 작업은 EMAIL_BASE_DIR로 제한됨

  • 경로 탐색 방지: 작업 공간 외부 파일에 대한 액세스 차단

  • 파일명 살균: 위험한 문자를 제거하고 예약된 이름을 처리

  • 크기 제한: 파일별 및 전체 첨부 파일 크기 제한 구성 가능

  • 파일 유형 검증: 첨부 파일 경로가 실제 파일을 가리키는지 확인

워크플로우 예시

다운로드 → 발송 워크플로우:

  1. download_attachment를 사용하여 이메일 첨부 파일을 downloads/에 저장

  2. 필요에 따라 파일을 uploads/로 이동하거나 복사

  3. send_email_with_attachments를 사용하여 uploads/에서 파일 발송

직접 업로드 워크플로우:

  1. 파일을 uploads/ 디렉터리에 배치

  2. 작업 공간 상대 경로를 사용하여 send_email_with_attachments 실행

구성

# Workspace directory (required for attachment operations)
EMAIL_BASE_DIR=/path/to/your/workspace

# Maximum attachment size per file (default: 50MB)
MAX_ATTACHMENT_SIZE_MB=50

배포

systemd를 사용하는 Ubuntu 서버

  1. 서버에 파일 복사:

scp -r email_mcp user@server:/home/user/
  1. Python 환경 설정:

ssh user@server
cd ~/email_mcp
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
  1. 원격 액세스 구성: .env 편집:

MCP_HOST=0.0.0.0  # Allow remote connections
MCP_BASE_URL=http://<your-server-ip>:8420  # Your server IP
  1. systemd 서비스 설치:

# Edit email-mcp.service to match your paths
sudo cp email-mcp.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable email-mcp
sudo systemctl start email-mcp
  1. 상태 확인:

sudo systemctl status email-mcp
sudo journalctl -u email-mcp -f  # View logs

MCP 클라이언트 구성

MCP 클라이언트 구성에 추가:

{
  "mcpServers": {
    "email": {
      "url": "http://localhost:8420/mcp",
      "headers": {
        "X-API-Key": "your-secret-api-key-here"
      }
    }
  }
}

원격 서버의 경우 http://<your-server-ip>:8420/mcp를 사용하세요 (서버 IP로 교체).

아키텍처

email_mcp/
├── main.py                 # FastAPI application entry point (HTTP/SSE mode)
├── mcp_server.py           # Stdio MCP entry point (MCPB / Claude Desktop mode)
├── config.py               # Pydantic settings (env vars)
├── auth.py                 # API key authentication middleware
├── imap/
│   ├── client.py          # IMAP connection pool
│   ├── read.py            # list_folders, read_email
│   ├── search.py          # search_emails
│   ├── flags.py           # mark_email, move_email
│   └── attachments.py     # download_attachment
├── smtp/
│   ├── client.py          # send_email, reply_email
│   └── attachments.py     # send_email_with_attachments
├── tools/
│   ├── definitions.py     # MCP tool schemas
│   ├── handlers.py        # Tool request routing
│   └── mcp_routes.py      # MCP HTTP endpoints
├── utils/
│   └── attachment_utils.py # Secure file handling utilities
└── tests/                  # 85+ unit and integration tests

주요 설계 패턴

  • 연결 풀링: asyncio.Semaphore를 사용하여 동시 IMAP 연결 제한 (기본값: 3)

  • 오류 처리: 구조화된 예외를 MCP 오류 응답으로 매핑

  • 이메일 스레딩: 답장 체인을 위한 In-Reply-To 및 References 헤더 사용

  • 멀티파트 메시지: 메시지 트리를 탐색하여 텍스트/HTML/첨부 파일 추출

  • 바이너리 전송 없음: 첨부 파일은 메타데이터(파일명, 크기, content_type)만 반환

문제 해결

Gmail 관련 설정

  1. IMAP 활성화: 설정 → 전달 및 POP/IMAP → IMAP 활성화

  2. 앱 비밀번호: 일반 비밀번호 대신 앱 비밀번호 사용

  3. Gmail SMTP: STARTTLS와 함께 smtp.gmail.com:587 사용

연결 문제

# Test IMAP connection
openssl s_client -connect imap.gmail.com:993

# Test SMTP connection
openssl s_client -starttls smtp -connect smtp.gmail.com:587

일반적인 오류

  • CONNECTION_TIMEOUT: IMAP_HOST 및 IMAP_PORT 확인

  • AUTH_FAILED: 자격 증명 확인, Gmail의 경우 앱 비밀번호 사용

  • FOLDER_NOT_FOUND: 폴더 이름은 대소문자를 구분함 (list_folders로 확인)

  • MESSAGE_NOT_FOUND: UID가 유효하지 않거나 메시지가 삭제되었을 수 있음

SMTPException - Connection already using TLS: 자동 모드의 경우 .env에서 SMTP_STARTTLS=none으로 설정하세요. 유효한 값은 none, true, false입니다.

개발

프로젝트 구조

  • imap/ - IMAP 클라이언트 및 도구 (읽기, 검색, 플래그)

  • smtp/ - SMTP 클라이언트 및 도구 (발송, 답장)

  • tools/ - MCP 엔드포인트 핸들러 및 스키마

  • tests/ - 단위 및 통합 테스트

개발 환경에서 실행

# Auto-reload on file changes
uvicorn main:app --reload --host 127.0.0.1 --port 8420

# Debug mode with verbose logging
LOG_LEVEL=DEBUG uvicorn main:app --host 127.0.0.1 --port 8420

새 도구 추가

  1. 적절한 모듈에 입력/출력을 위한 Pydantic 모델 정의

  2. 오류 처리를 포함한 비동기 함수 구현

  3. tools/definitions.py에 도구 스키마 추가

  4. tools/mcp_routes.py에 디스패처 연결

  5. TDD 방식에 따라 테스트 작성

라이선스

MIT

기여

기여를 환영합니다! 다음 사항을 준수해 주세요:

  1. 모든 새 기능에 대한 테스트 작성

  2. 기존 코드 스타일(black, isort, mypy) 준수

  3. 중요한 변경 사항에 대해 이 README 업데이트

  4. PR 제출 전 모든 테스트 통과 확인

지원

문제, 질문 또는 기능 요청은 GitHub에 이슈를 열어주세요.

-
security - not tested
A
license - permissive license
-
quality - not tested

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

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/pzanna/email_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server