Skip to main content
Glama
AbhinavBansal17

MCP Headless Gmail Server

gmail_send_email

Send emails through Gmail with optional file attachments using OAuth tokens in headless environments, enabling automated email dispatch without local credential storage.

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

  • Registration of the 'gmail_send_email' tool including its input schema definition in the list_tools() handler.
    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"] }, ),
  • Dispatch handler for 'gmail_send_email' tool call within the @server.call_tool() function. Initializes GmailClient and invokes the send_email method.
    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)]
  • Core helper method in GmailClient class that implements the email sending logic using Google Gmail API, including support for HTML body and attachments.
    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)})
  • server.js:358-378 (registration)
    Registration and inline handler for 'gmail_send_email' tool in JavaScript implementation using Zod schema.
    server.tool( 'gmail_send_email', 'Send an email via Gmail', { google_access_token: z.string().describe('Google OAuth2 access token'), to: z.string().describe('Recipient email address'), subject: z.string().describe('Email subject'), body: z.string().describe('Email body content (plain text)'), html_body: z.string().optional().describe('Email body content in HTML format (optional)') }, async ({ google_access_token, to, subject, body, html_body }) => { try { const gmail = new GmailClient({ accessToken: google_access_token }); const result = await gmail.sendEmail({ to, subject, body, html_body }); return { content: [{ type: 'text', text: result }] }; } catch (error) { return { content: [{ type: 'text', text: `Error: ${error.message}` }] }; } }
  • Core helper method in GmailClient class for sending email in the JavaScript implementation.
    async sendEmail({ to, subject, body, html_body }) { const operation = async () => { if (!this.gmail) { throw new Error('Gmail service not initialized. No valid access token provided.'); } const messageParts = [ `To: ${to}`, `Subject: ${subject}`, 'Content-Type: multipart/alternative; boundary="boundary"', '', '--boundary', 'Content-Type: text/plain; charset="UTF-8"', '', body, '--boundary', 'Content-Type: text/html; charset="UTF-8"', '', html_body || '', '--boundary--' ]; const rawMessage = Buffer.from(messageParts.join('\r\n')).toString('base64').replace(/\+/g, '-').replace(/\//g, '_'); const res = await this.gmail.users.messages.send({ userId: 'me', requestBody: { raw: rawMessage } }); return JSON.stringify({ messageId: res.data.id, threadId: res.data.threadId, labelIds: res.data.labelIds }); }; return await this._handleTokenRefresh(operation); }

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