Integrations
Allows AI assistants to interact with Gmail via IMAP, supporting email listing, searching, reading (with attachments), sending, and managing labels and folders through OAuth2 authentication.
Used for OAuth authentication to access Gmail services, requiring configuration of a Google Cloud Project with OAuth consent screen and credentials.
Gmail IMAP MCP Server
A Model Context Protocol (MCP) server for Gmail integration using IMAP. This server allows AI assistants to interact with Gmail accounts, providing functionality to read, search, and manage emails.
Features
- OAuth2 authentication with Gmail
- Read emails from Gmail accounts with advanced search capabilities
- Search emails with comprehensive filtering (dates, labels, keywords, etc.)
- Special handling for contact form emails
- View unread emails with additional filtering options
- Send emails with attachments
- Manage labels (create, delete, list)
- Move emails between labels
- Download attachments
- Mark emails as read/unread
- Support for multiple Gmail accounts
- Integration with AI assistants through MCP
- Backtick handling for better Claude compatibility
Prerequisites
Before running the Gmail IMAP MCP server, ensure you have the following:
- Python 3.12 or higher
- Google Cloud Project with Gmail API enabled
- OAuth 2.0 Client ID credentials
Installation
Install from source
- Clone the repository:Copy
- Create and activate a virtual environment:Copy
- Install the package:Copy
Setup Google Cloud Project
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the Gmail API for your project:
- Navigate to "APIs & Services" > "Library"
- Search for "Gmail API" and enable it
- Create OAuth 2.0 credentials:
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth client ID"
- Choose "Desktop app" as application type
- Download the client configuration file
- Save the downloaded file as
client_secret.json
in the credentials directory:Copy
Recent Enhancements
Enhanced Search Functionality
The Gmail IMAP MCP server now features significantly improved search capabilities:
- Gmail-Style Query Syntax: Use Gmail-style queries like
from:example@gmail.com is:unread has:attachment
- Special Characters Support: Query labels with special characters (e.g.,
label:$$$$$
) - Date Range Filtering: Search emails by date ranges with
after_date
andbefore_date
parameters - Combined Filtering: Mix and match search criteria for precise email filtering
- Additional Search Parameters: Filter by read/unread status, attachments, etc.
Contact Form Email Processing
Special handling for emails sent from contact forms:
- Automated Detection: Identifies emails sent from website contact forms
- True Sender Extraction: Extracts the actual sender from Reply-To headers or embedded From lines
- Website Source Identification: Shows which website the contact form came from
- Clean Message Extraction: Extracts just the message content, removing form metadata
- Improved Display Format: Shows contact form emails in a clear, structured format
Backtick JSON Handling
Added support for handling Claude's tendency to use backticks in JSON:
- Automatic Conversion: Converts backtick-formatted JSON (
name
) to proper JSON ("name") - Error Handling: Provides helpful error messages about JSON format issues
- Seamless Integration: Works automatically, no special handling needed
Claude Desktop Guide
This section provides guidance specifically for Claude Desktop when using the Gmail MCP Server. It highlights key tools and best practices for effective email handling.
Key Tools and Functions
1. Reply Functions (CRITICAL)
Two distinct reply functions are available, each serving a specific purpose:
- reply-to-message: For responding to newly arrived emails that don't have previous back-and-forth communication.
- reply-to-thread: For continuing existing conversations where there is already back-and-forth communication.
IMPORTANT: Always use the appropriate reply function:
- Use
reply-to-message
for initial responses to new messages - Use
reply-to-thread
for continuing existing conversations - Using
send-email
instead will break email threading and create disconnected conversations
2. Email Content Retrieval
- get-email: Always use this tool to retrieve full email content including body, headers, and true sender information for contact forms before responding.
Best Practices for Claude
- Always Get Full Email Content: Before responding, always use
get-email
to see the complete message including true sender information. - Use Proper Reply Functions: Never use
send-email
when responding to existing emails as it breaks threading. Use the appropriate reply function instead. - Handle Contact Forms Correctly: For contact form submissions, check for true sender information in the email content that comes from
get-email
. - Mark Emails as Read: Always mark emails as read after handling them to avoid duplicate responses.
- Thread Management: Use
reply-to-thread
when continuing existing conversations to maintain proper email threading.
Special Cases
Contact Form Emails
When handling contact form emails:
- Look for "True Sender" information provided by the enhanced parser
- Reply to the true sender rather than the form submission address
- Maintain appropriate professional tone as you're representing the business
Email IDs and Resource URIs
When working with email IDs, you may encounter two formats:
- Raw IDs (e.g.,
12345
) - Resource URIs (e.g.,
email://message/account_INBOX_12345
)
All tools have been updated to handle both formats correctly.
Recommended Workflow
- Search for unread emails using
get-unread-emails
- For each unread email, use
get-email
to retrieve the full content - Determine if this is a new conversation or continuation of an existing thread
- Use the appropriate reply function (
reply-to-message
orreply-to-thread
) - Mark the email as read using
mark-as-read
Remember, Claude's primary job is to properly respond to emails, not to initiate new conversations. Always use the correct reply function to maintain proper email threading!
Tools Reference
Authentication
authenticate-gmail
: Authenticate a Gmail account for MCP use
Email Retrieval
search-emails
: Search for emails with advanced filteringget-unread-emails
: Get unread emails with additional filtering optionsget-email
: Get full details of a specific email
Email Sending
send-email
: Send a new email with optional attachmentsreply-to-message
: Reply to a specific emailreply-to-thread
: Reply to an email thread (most recent message)
Label Management
list-labels
: List all available labelscreate-label
: Create a new labeldelete-label
: Delete an existing labelmove-email
: Move emails between labels
Email Organization
download-attachment
: Download email attachmentsmark-as-read
: Mark an email as readmark-as-unread
: Mark an email as unread
Advanced Usage Examples
Enhanced Search with Date Range and Label
Get Unread Emails with Additional Filtering
Search with Complex Gmail Query
Architecture and Implementation Details
Credential Storage
The Gmail IMAP MCP server stores OAuth2 credentials in the user's home directory at ~/.gmail_imap_mcp_credentials/
. This approach offers several advantages:
- Security: Credentials are stored in a user-specific location rather than in the application directory
- Persistence: Credentials persist across different sessions and application restarts
- Compatibility: Avoids permission issues on read-only file systems
The credentials directory contains:
client_secret.json
: Your OAuth client credentials from Google Cloud Console- Token files for each authenticated Gmail account (format:
token_{email_address}.json
)
IMAP Implementation
The server uses Python's imaplib2
library for IMAP operations with Gmail. Key implementation details include:
- Connection: Secure connection to Gmail's IMAP server (
imap.gmail.com
) on port 993 - Authentication: OAuth2 authentication using XOAUTH2 mechanism
- Email Retrieval: Emails are retrieved using RFC822 format and parsed with Python's
email
module - Label Management: Gmail labels are managed through IMAP mailbox operations
- Gmail Query Parsing: Gmail-style queries are intelligently converted to IMAP search criteria
Email ID Format
Email IDs in the system follow this format:
Where:
{account}
: The Gmail account address{mailbox}
: The mailbox/label containing the email{id}
: The unique IMAP ID of the email
This format allows the system to uniquely identify emails across different accounts and mailboxes.
Contributing
Contributions to improve the Gmail IMAP MCP server are welcome! Please feel free to submit issues or pull requests.
Usage
Starting the Server
Run the Gmail IMAP MCP server:
Authenticating Gmail Accounts
- Use the
authenticate-gmail
tool with your email address - Follow the OAuth2 authentication flow in your browser
- Once authenticated, the server will store your credentials for future use
Available Tools and Examples
The Gmail IMAP MCP server provides a comprehensive set of tools for interacting with Gmail accounts. Below is a detailed list of all available tools along with examples of how to use them.
Authentication
1. authenticate-gmail
Authenticate a Gmail account to use with the MCP server.
Parameters:
email
: Email address to authenticate
Example:
Email Retrieval and Search
2. search-emails
Search for emails in a Gmail account using various search criteria.
Parameters:
account
: Email account to search inmailbox
: Mailbox to search in (default: INBOX)query
: Search querylimit
: Maximum number of emails to return (default: 10)
Example - Search for emails from a specific sender:
Example - Search for emails with a specific subject:
Example - Search for emails with specific text in the body:
3. get-unread-emails
Get unread emails from a Gmail account.
Parameters:
account
: Email account to get emails frommailbox
: Mailbox to get emails from (default: INBOX)limit
: Maximum number of emails to return (default: 10)
Example:
Email Composition and Sending
4. send-email
Send an email from a Gmail account with optional attachments and HTML content.
Parameters:
account
: Email account to send fromto
: Recipient email address(es), comma-separated for multiplesubject
: Email subjectbody
: Plain text email bodycc
: Carbon copy recipients (optional)bcc
: Blind carbon copy recipients (optional)html_body
: HTML version of the email body (optional)attachments
: List of attachment objects (optional)- Each attachment object requires:
path
: Path to the filefilename
: Custom filename (optional)content_type
: MIME type (optional)
- Each attachment object requires:
Example - Simple email:
Example - Email with CC, BCC, and HTML content:
Example - Email with attachment:
5. reply-to-message
Reply to a specific email message with optional attachments and HTML content.
Parameters:
account
: Email account to reply fromemail_id
: Email ID to reply to (format:email://message/{account}_{mailbox}_{id}
or raw ID)body
: Plain text reply bodymailbox
: Mailbox containing the email (default: INBOX)html_body
: HTML version of the reply (optional)attachments
: List of attachment objects (optional)- Each attachment object requires:
path
: Path to the filefilename
: Custom filename (optional)content_type
: MIME type (optional)
- Each attachment object requires:
Example - Simple reply:
Example - Reply with attachment:
6. reply-to-thread
Reply to an email thread (using the most recent message in the thread) with optional attachments and HTML content.
Parameters:
account
: Email account to reply fromthread_id
: Thread ID to reply to (format:email://message/{account}_{mailbox}_{id}
or raw ID)body
: Plain text reply bodymailbox
: Mailbox containing the thread (default: INBOX)html_body
: HTML version of the reply (optional)attachments
: List of attachment objects (optional)- Each attachment object requires:
path
: Path to the filefilename
: Custom filename (optional)content_type
: MIME type (optional)
- Each attachment object requires:
Example - Simple thread reply:
Label Management
7. create-label
Create a new label/mailbox in a Gmail account.
Parameters:
account
: Email account to create label inlabel_name
: Name of the label to create
Example:
8. delete-label
Delete a label/mailbox from a Gmail account.
Parameters:
account
: Email account to delete label fromlabel_name
: Name of the label to delete
Example:
9. list-labels
List all labels/mailboxes in a Gmail account.
Parameters:
account
: Email account to list labels from
Example:
Email Organization
10. move-email
Move an email from one label/mailbox to another.
Parameters:
account
: Email accountemail_id
: Email ID to move (format:email://message/{account}_{mailbox}_{id}
)source_mailbox
: Source mailboxtarget_mailbox
: Target mailbox
Example:
Attachment Handling
11. download-attachment
Download an attachment from an email.
Parameters:
account
: Email accountemail_id
: Email ID (format:email://message/{account}_{mailbox}_{id}
)attachment_index
: Index of the attachment to download (0-based)mailbox
: Mailbox containing the email (default: INBOX)download_dir
: Directory to save the attachment to (default: "downloads")
Example:
Email Status Management
12. mark-as-read
Mark an email as read.
Parameters:
account
: Email accountemail_id
: Email ID (format:email://message/{account}_{mailbox}_{id}
)mailbox
: Mailbox containing the email (default: INBOX)
Example:
13. mark-as-unread
Mark an email as unread.
Parameters:
account
: Email accountemail_id
: Email ID (format:email://message/{account}_{mailbox}_{id}
)mailbox
: Mailbox containing the email (default: INBOX)
Example:
Available Prompts
The server provides the following prompts for AI assistants to use:
1. summarize-emails
Creates a summary of recent emails.
Parameters:
account
: Email account to summarizemailbox
: Mailbox to summarize (default: INBOX)count
: Number of emails to summarize (default: 5)
Example:
Integration with AI Assistants
The Gmail IMAP MCP server can be integrated with AI assistants that support the Model Context Protocol (MCP). Here's a typical workflow:
- Authentication: The AI assistant uses the
authenticate-gmail
tool to authenticate the user's Gmail account. - Email Management: The assistant can retrieve, search, and manage emails using the various tools provided by the server.
- Email Composition: The assistant can help draft and send emails based on user instructions.
- Email Organization: The assistant can help organize emails by creating labels, moving emails between labels, and marking emails as read/unread.
- Email Summarization: The assistant can summarize emails using the
summarize-emails
prompt.
Connecting with AI Assistants
Claude Desktop
To connect the Gmail IMAP MCP server with Claude Desktop:
- Start the Gmail IMAP MCP server:Copy
- Open Claude Desktop and navigate to Settings (gear icon)
- Scroll down to the "Advanced" section and click on "Edit MCP Configuration"
- Add the Gmail IMAP MCP server configuration:Copy
- Click "Save" and restart Claude Desktop
- You can now ask Claude to interact with your Gmail account. For best results, refer to the "Claude Desktop Guide" section above for proper usage of reply functions and email handling best practices.Recommended tasks to try:
- "Show me my unread emails"
- "Get the full content of email [ID]"
- "Reply to this email with [content]"
- "Continue this email thread with [content]"
- "Mark this email as read"
- "Search for emails from [sender]"
IMPORTANT NOTE: For email replies, always use the proper reply functions (reply-to-message
or reply-to-thread
) rather than send-email
to maintain proper email threading!
Windsurf IDE
To connect the Gmail IMAP MCP server with Windsurf IDE:
- Start the Gmail IMAP MCP server:Copy
- Open Windsurf IDE and navigate to Settings
- Find the "AI Flow" or "MCP Configuration" section
- Add the Gmail IMAP MCP server configuration:Copy
- Save the settings and restart Windsurf if necessary
- You can now ask Cascade (Windsurf's AI assistant) to interact with your Gmail account using the same commands as with Claude Desktop
Common Use Cases
1. Email Triage
2. Email Search and Organization
3. Email Composition
Gmail-Specific Considerations
Label Naming Conventions
Gmail has specific requirements for label names:
- Label names are case-sensitive
- Some special characters may not be allowed
- System labels (like INBOX, Sent, Trash) cannot be created or deleted
- Nested labels are represented with a forward slash (e.g., "Projects/ProjectX")
Email ID Format
The email ID format used by this MCP server is:
When using tools that require an email ID (like mark-as-read
or move-email
), make sure to use the complete resource URI returned by email retrieval tools.
Security Considerations
- The server stores OAuth2 credentials locally in the
~/.gmail_imap_mcp_credentials
directory - Never share your
client_secret.json
or token files - The server only connects to Gmail's IMAP server using secure connections
- Email attachments are downloaded to the
downloads
directory by default - Be cautious when using the server in shared environments to protect email data
Troubleshooting
Authentication Issues
- Ensure your
client_secret.json
is correctly placed in the~/.gmail_imap_mcp_credentials
directory - Check that you've enabled the Gmail API in your Google Cloud Project
- Try re-authenticating if your token has expired
- If you see "Read-only file system" errors, ensure the credentials directory is writable
Connection Issues
- Verify your internet connection
- Ensure that your Google account doesn't have any security restrictions that might block IMAP access
- Check if you need to enable "Less secure app access" in your Google account settings
Email Sending Issues
- Verify that your Gmail account allows SMTP access
- Check if you need to enable "Less secure app access" in your Google account settings
- Ensure attachments are not too large (Gmail has a 25MB limit)
Label Management Issues
- If creating labels fails, check if the label already exists (case-sensitive)
- System labels cannot be created or deleted
- Ensure label names follow Gmail's naming conventions
Email Movement Issues
- If moving emails between labels fails, ensure both source and target labels exist
- Check that the email ID format is correct
- Verify that you have sufficient permissions to modify the email
Email ID Parsing Issues
- If operations on email IDs fail, ensure you're using the complete resource URI
- The system parses the last part of the URI as the actual email ID
- Format should be:
email://message/{account}_{mailbox}_{id}
License
Support
For issues and feature requests, please open an issue on the GitHub repository.
Command Line Interface
In addition to the MCP server, this package also provides a command-line interface (CLI) for direct interaction with Gmail accounts.
Installation
The CLI is automatically installed when you install the package:
Available Commands
1. Authenticate a Gmail account
2. Reply to a specific message
3. Reply to a thread
CLI Arguments
The CLI supports the following arguments for replying to messages and threads:
account
: Gmail account to useemail_id
/thread_id
: Email/Thread ID to reply tobody
: Reply message body (plain text)--mailbox
: Mailbox containing the email/thread (default: INBOX)--html
: HTML version of the reply body--attachments
: One or more file paths to attach to the reply
This server cannot be installed
local-only server
The server can only run on the client's local machine because it depends on local resources.
Enables AI assistants to interact with Gmail accounts via IMAP, allowing them to list, search, read, and send emails, manage labels and folders, and access attachments through the Model Context Protocol.
- Features
- Prerequisites
- Installation
- Setup Google Cloud Project
- Recent Enhancements
- Claude Desktop Guide
- Tools Reference
- Advanced Usage Examples
- Architecture and Implementation Details
- Contributing
- Usage
- Available Tools and Examples
- Available Prompts
- Integration with AI Assistants
- Connecting with AI Assistants
- Common Use Cases
- Gmail-Specific Considerations
- Security Considerations
- Troubleshooting
- License
- Support
- Command Line Interface