Skip to main content
Glama
ai-zerolab

MCP Email Server

by ai-zerolab

get_emails_content

Retrieve complete email content including body text using email IDs obtained from metadata listings. This tool extracts full messages for analysis or processing.

Instructions

Get the full content (including body) of one or more emails by their email_id. Use list_emails_metadata first to get the email_id.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
account_nameYesThe name of the email account.
email_idsYesList of email_id to retrieve (obtained from list_emails_metadata). Can be a single email_id or multiple email_ids.
mailboxNoThe mailbox to retrieve emails from.INBOX

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
emailsYes
failed_idsYes
requested_countYes
retrieved_countYes

Implementation Reference

  • The primary handler function in ClassicEmailHandler that orchestrates batch retrieval of email contents by ID. Fetches individual emails, handles errors, constructs response objects, and reports failures.
    async def get_emails_content(self, email_ids: list[str], mailbox: str = "INBOX") -> EmailContentBatchResponse:
        """Batch retrieve email body content"""
        emails = []
        failed_ids = []
    
        for email_id in email_ids:
            try:
                email_data = await self.incoming_client.get_email_body_by_id(email_id, mailbox)
                if email_data:
                    emails.append(
                        EmailBodyResponse(
                            email_id=email_data["email_id"],
                            message_id=email_data.get("message_id"),
                            subject=email_data["subject"],
                            sender=email_data["from"],
                            recipients=email_data["to"],
                            date=email_data["date"],
                            body=email_data["body"],
                            attachments=email_data["attachments"],
                        )
                    )
                else:
                    failed_ids.append(email_id)
            except Exception as e:
                logger.error(f"Failed to retrieve email {email_id}: {e}")
                failed_ids.append(email_id)
    
        return EmailContentBatchResponse(
            emails=emails,
            requested_count=len(email_ids),
            retrieved_count=len(emails),
            failed_ids=failed_ids,
        )
  • MCP tool registration using FastMCP @mcp.tool decorator. Defines input parameters with descriptions and types (schema), and delegates execution to the dispatched handler.
    @mcp.tool(
        description="Get the full content (including body) of one or more emails by their email_id. Use list_emails_metadata first to get the email_id."
    )
    async def get_emails_content(
        account_name: Annotated[str, Field(description="The name of the email account.")],
        email_ids: Annotated[
            list[str],
            Field(
                description="List of email_id to retrieve (obtained from list_emails_metadata). Can be a single email_id or multiple email_ids."
            ),
        ],
        mailbox: Annotated[str, Field(default="INBOX", description="The mailbox to retrieve emails from.")] = "INBOX",
    ) -> EmailContentBatchResponse:
        handler = dispatch_handler(account_name)
        return await handler.get_emails_content(email_ids, mailbox)
  • EmailClient method called by handler to fetch a single email's full content via IMAP UID fetch (trying multiple formats), extract raw bytes, and parse into structured data.
    async def get_email_body_by_id(self, email_id: str, mailbox: str = "INBOX") -> dict[str, Any] | None:
        imap = self.imap_class(self.email_server.host, self.email_server.port)
        try:
            # Wait for the connection to be established
            await imap._client_task
            await imap.wait_hello_from_server()
    
            # Login and select inbox
            await imap.login(self.email_server.user_name, self.email_server.password)
            try:
                await imap.id(name="mcp-email-server", version="1.0.0")
            except Exception as e:
                logger.warning(f"IMAP ID command failed: {e!s}")
            await imap.select(mailbox)
    
            # Fetch the specific email by UID
            data = await self._fetch_email_with_formats(imap, email_id)
            if not data:
                logger.error(f"Failed to fetch UID {email_id} with any format")
                return None
    
            # Extract raw email data
            raw_email = self._extract_raw_email(data)
            if not raw_email:
                logger.error(f"Could not find email data in response for email ID: {email_id}")
                return None
    
            # Parse the email
            try:
                return self._parse_email_data(raw_email, email_id)
            except Exception as e:
                logger.error(f"Error parsing email: {e!s}")
                return None
  • Dispatches to the appropriate EmailHandler implementation (currently only ClassicEmailHandler) based on account settings.
    def dispatch_handler(account_name: str) -> EmailHandler:
        settings = get_settings()
        account = settings.get_account(account_name)
        if isinstance(account, ProviderSettings):
            raise NotImplementedError
        if isinstance(account, EmailSettings):
            return ClassicEmailHandler(account)
    
        raise ValueError(f"Account {account_name} not found, available accounts: {settings.get_accounts()}")
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It clearly indicates this is a read operation ('Get'), but doesn't mention authentication requirements, rate limits, error conditions, or what happens with invalid email_ids. The description adds value by specifying content scope but lacks comprehensive behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly concise with two sentences that each serve a distinct purpose: the first states what the tool does, the second provides crucial usage guidance. There's zero wasted language, and the most important information is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given that an output schema exists (so return values are documented elsewhere), the description provides adequate context for this read operation. It covers purpose, resource, and workflow sequencing. The main gap is lack of behavioral details like authentication or error handling, but with output schema covering returns, this is reasonably complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already fully documents all three parameters. The description adds minimal value beyond the schema by implying email_ids come from list_emails_metadata, but doesn't provide additional semantic context about parameter usage or constraints beyond what's in the schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Get the full content'), identifies the resource ('emails'), and specifies what content is retrieved ('including body'). It distinguishes from sibling tools like list_emails_metadata by focusing on content retrieval rather than metadata listing.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states when to use this tool ('by their email_id') and provides a clear alternative/predecessor ('Use list_emails_metadata first to get the email_id'). This gives the agent specific guidance on workflow sequencing and distinguishes it from other email-related tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/ai-zerolab/mcp-email-server'

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