Skip to main content
Glama
AbhinavBansal17

MCP Headless Gmail Server

gmail_send_email

Send emails through Gmail with optional file attachments, using OAuth tokens for secure, headless automation in remote environments.

Instructions

Send an email via Gmail with optional file attachments

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
google_access_tokenNoGoogle OAuth2 access token
toYesRecipient email address
subjectYesEmail subject
bodyYesEmail body content (plain text)
html_bodyNoEmail body content in HTML format (optional)
attachmentsNoOptional list of file attachments

Implementation Reference

  • Core handler function that constructs MIME message (handling plain/HTML body and attachments), base64 encodes it, and sends via Gmail API using googleapiclient.
    def send_email(self, to: str, subject: str, body: str, html_body: Optional[str] = None, 
                   attachments: Optional[List[Dict[str, str]]] = None) -> str:
        """Send an email via Gmail
        
        Args:
            to: Recipient email address
            subject: Email subject
            body: Plain text email body
            html_body: Optional HTML email body
            attachments: Optional list of attachment dictionaries with keys:
                        - 'filename': Name of the file
                        - 'data': Base64 URL encoded file data
                        - 'mime_type': MIME type of the file (optional, will be inferred if not provided)
        """
        try:
            # Check if service is initialized
            if not hasattr(self, 'service'):
                return json.dumps({
                    "error": "No valid access token provided. Please refresh your token first.",
                    "status": "error"
                })
                
            # Define the operation
            def _operation():
                # Create message container - use 'mixed' if we have attachments, 'alternative' otherwise
                if attachments:
                    message = MIMEMultipart('mixed')
                else:
                    message = MIMEMultipart('alternative')
                
                message['to'] = to
                message['subject'] = subject
                
                # Create the text/html part container
                if attachments:
                    text_part = MIMEMultipart('alternative')
                    message.attach(text_part)
                    text_part.attach(MIMEText(body, 'plain'))
                    if html_body:
                        text_part.attach(MIMEText(html_body, 'html'))
                else:
                    # Attach plain text and HTML parts directly
                    message.attach(MIMEText(body, 'plain'))
                    if html_body:
                        message.attach(MIMEText(html_body, 'html'))
                
                # Add attachments if provided
                if attachments:
                    for attachment in attachments:
                        try:
                            filename = attachment.get('filename', 'attachment')
                            file_data = attachment.get('data', '')
                            mime_type = attachment.get('mime_type')
                            
                            if not file_data:
                                logger.warning(f"Skipping attachment {filename}: no data provided")
                                continue
                            
                            # Decode base64 URL encoded data
                            try:
                                decoded_data = base64.urlsafe_b64decode(file_data)
                            except Exception as e:
                                logger.error(f"Failed to decode base64 data for {filename}: {str(e)}")
                                continue
                            
                            # Determine MIME type if not provided
                            if not mime_type:
                                import mimetypes
                                mime_type, _ = mimetypes.guess_type(filename)
                                if not mime_type:
                                    mime_type = 'application/octet-stream'
                            
                            # Create attachment
                            attachment_part = MIMEApplication(decoded_data, _subtype=mime_type.split('/')[-1])
                            attachment_part.add_header('Content-Disposition', 'attachment', filename=filename)
                            message.attach(attachment_part)
                            
                            logger.debug(f"Successfully attached {filename} ({len(decoded_data)} bytes)")
                            
                        except Exception as e:
                            logger.error(f"Error processing attachment {filename}: {str(e)}")
                            continue
                
                # Encode the message
                encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
                
                # Create the message body
                create_message = {
                    'raw': encoded_message
                }
                
                # Send the message
                send_response = self.service.users().messages().send(
                    userId='me', 
                    body=create_message
                ).execute()
                
                return json.dumps({
                    "messageId": send_response['id'],
                    "threadId": send_response.get('threadId', ''),
                    "labelIds": send_response.get('labelIds', [])
                })
            
            # Execute the operation with token refresh handling
            return _operation()
            
        except HttpError as e:
            logger.error(f"API Exception: {str(e)}")
            return json.dumps({"error": str(e)})
        except Exception as e:
            logger.error(f"Exception: {str(e)}")
            return json.dumps({"error": str(e)})
  • MCP server.call_tool dispatch handler for 'gmail_send_email': extracts arguments, initializes GmailClient, validates inputs, calls the send_email method, and returns result.
    elif name == "gmail_send_email":
        # Initialize Gmail client with just access token
        gmail = GmailClient(
            access_token=access_token
        )
        
        to = arguments.get("to")
        subject = arguments.get("subject")
        body = arguments.get("body")
        html_body = arguments.get("html_body")
        attachments = arguments.get("attachments")
        
        if not to or not subject or not body:
            raise ValueError("Missing required parameters: to, subject, and body are required")
        
        results = gmail.send_email(to=to, subject=subject, body=body, html_body=html_body, attachments=attachments)
        return [types.TextContent(type="text", text=results)]
  • Input schema for the gmail_send_email tool defining parameters like to, subject, body, optional html_body and attachments array.
    inputSchema={
        "type": "object",
        "properties": {
            "google_access_token": {"type": "string", "description": "Google OAuth2 access token"},
            "to": {"type": "string", "description": "Recipient email address"},
            "subject": {"type": "string", "description": "Email subject"},
            "body": {"type": "string", "description": "Email body content (plain text)"},
            "html_body": {"type": "string", "description": "Email body content in HTML format (optional)"},
            "attachments": {
                "type": "array",
                "description": "Optional list of file attachments",
                "items": {
                    "type": "object",
                    "properties": {
                        "filename": {"type": "string", "description": "Name of the file"},
                        "data": {"type": "string", "description": "Base64 URL encoded file data"},
                        "mime_type": {"type": "string", "description": "MIME type of the file (optional, will be inferred if not provided)"}
                    },
                    "required": ["filename", "data"]
                }
            }
        },
        "required": ["to", "subject", "body"]
    },
  • Tool registration in server.list_tools() defining name, description, and schema for gmail_send_email.
        types.Tool(
            name="gmail_send_email",
            description="Send an email via Gmail with optional file attachments",
            inputSchema={
                "type": "object",
                "properties": {
                    "google_access_token": {"type": "string", "description": "Google OAuth2 access token"},
                    "to": {"type": "string", "description": "Recipient email address"},
                    "subject": {"type": "string", "description": "Email subject"},
                    "body": {"type": "string", "description": "Email body content (plain text)"},
                    "html_body": {"type": "string", "description": "Email body content in HTML format (optional)"},
                    "attachments": {
                        "type": "array",
                        "description": "Optional list of file attachments",
                        "items": {
                            "type": "object",
                            "properties": {
                                "filename": {"type": "string", "description": "Name of the file"},
                                "data": {"type": "string", "description": "Base64 URL encoded file data"},
                                "mime_type": {"type": "string", "description": "MIME type of the file (optional, will be inferred if not provided)"}
                            },
                            "required": ["filename", "data"]
                        }
                    }
                },
                "required": ["to", "subject", "body"]
            },
        ),
    ]
Behavior2/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 states this is a send operation (implying mutation/write) but doesn't mention authentication requirements (though the schema shows google_access_token parameter), rate limits, error conditions, what happens on success/failure, or whether emails are sent immediately or queued. The description adds minimal behavioral context beyond what's implied by 'send'.

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 a single, efficient sentence that states the core purpose and key feature (attachments) with zero wasted words. It's appropriately sized and front-loaded with the essential information.

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

Completeness2/5

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

For a mutation tool with no annotations and no output schema, the description is insufficient. It doesn't explain what happens after sending (success/failure indicators), authentication requirements, rate limits, or error handling. The 100% schema coverage helps with parameters, but behavioral aspects are largely undocumented given this is a write operation with potential side effects.

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 documents all 6 parameters thoroughly. The description adds value by mentioning 'optional file attachments' which helps contextualize the attachments parameter, but doesn't provide additional semantic context beyond what's in the schema descriptions. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the action ('send an email') and resource ('via Gmail') with a specific feature mention ('optional file attachments'). It distinguishes from sibling tools (gmail_get_email_body_chunk, gmail_get_recent_emails) by being a write operation rather than a read operation, though it doesn't explicitly name the siblings for comparison.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives or when not to use it. It mentions 'optional file attachments' but doesn't explain when to use attachments versus inline content, nor does it reference the sibling tools for different email-related tasks.

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/AbhinavBansal17/mcp-headless-gmail'

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