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"] }, ), ]

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