Skip to main content
Glama
by ricleedo

gmail-get-email

Retrieve specific Gmail messages by message ID to access email content and details directly from your Gmail account.

Instructions

Get a specific email by message ID

Input Schema

NameRequiredDescriptionDefault
messageIdYesGmail message ID

Input Schema (JSON Schema)

{ "properties": { "messageId": { "description": "Gmail message ID", "type": "string" } }, "required": [ "messageId" ], "type": "object" }

Implementation Reference

  • src/index.ts:200-207 (registration)
    Registration of the 'gmail-get-email' tool in the MCP server, delegating to the imported getEmail handler.
    server.tool( "gmail-get-email", "Get a specific email by message ID", getEmailSchema.shape, async (params) => { return await getEmail(params); } );
  • Zod input schema defining the required 'messageId' parameter for the tool.
    export const getEmailSchema = z.object({ messageId: z.string().describe("Gmail message ID"), });
  • Core handler implementation: Fetches a specific Gmail message by ID using the Google API, extracts headers and body (handling multipart), formats it to Markdown, and returns structured content.
    export async function getEmail(params: z.infer<typeof getEmailSchema>) { try { const auth = createGmailAuth(); const gmail = google.gmail({ version: "v1", auth }); const response = await gmail.users.messages.get({ userId: "me", id: params.messageId, format: "full", }); const message = response.data; const headers = message.payload?.headers || []; const getHeader = (name: string) => headers.find((h) => h.name?.toLowerCase() === name.toLowerCase()) ?.value || ""; // Extract body content let body = ""; if (message.payload?.body?.data) { body = Buffer.from(message.payload.body.data, "base64").toString(); } else if (message.payload?.parts) { // Handle multipart messages for (const part of message.payload.parts) { if (part.mimeType === "text/plain" && part.body?.data) { body = Buffer.from(part.body.data, "base64").toString(); break; } } } // Truncate body if it exceeds 30000 characters const truncatedBody = body.length > 20000 ? body.substring(0, 20000) + "\n\n[Email body truncated - content too long]" : body; const emailDetail = { id: message.id, threadId: message.threadId, from: getHeader("From"), to: getHeader("To"), cc: getHeader("Cc"), bcc: getHeader("Bcc"), subject: getHeader("Subject"), date: getHeader("Date"), body: truncatedBody, snippet: message.snippet, labelIds: message.labelIds, }; return { content: [ { type: "text" as const, text: formatEmailToMarkdown(emailDetail), }, ], }; } catch (error) { return { content: [ { type: "text" as const, text: `Error getting email: ${ error instanceof Error ? error.message : String(error) }`, }, ], }; } }
  • Helper function used by getEmail to format the retrieved email details into a readable Markdown structure.
    function formatEmailToMarkdown(email: any): string { const date = new Date(email.date).toLocaleDateString(); const from = email.from.replace(/[<>]/g, ''); const to = email.to.replace(/[<>]/g, ''); const subject = email.subject || '(No Subject)'; let markdown = `# ${subject}\n\n`; markdown += `From: ${from} \n`; markdown += `To: ${to} \n`; if (email.cc) markdown += `CC: ${email.cc.replace(/[<>]/g, '')} \n`; if (email.bcc) markdown += `BCC: ${email.bcc.replace(/[<>]/g, '')} \n`; markdown += `Date: ${date} \n`; markdown += `Message ID: \`${email.id}\`\n\n`; if (email.body) { markdown += `---\n\n${email.body}\n`; } return markdown; }
  • Shared authentication helper for Gmail API calls, using environment variables for OAuth2 credentials.
    function createGmailAuth() { const clientId = process.env.GOOGLE_CLIENT_ID; const clientSecret = process.env.GOOGLE_CLIENT_SECRET; const redirectUri = process.env.GOOGLE_REDIRECT_URI || "http://localhost:3000/oauth2callback"; if (!clientId || !clientSecret) { throw new Error( "GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are required. Run oauth-setup.js to configure." ); } const oauth2Client = new google.auth.OAuth2( clientId, clientSecret, redirectUri ); const accessToken = process.env.GOOGLE_ACCESS_TOKEN; const refreshToken = process.env.GOOGLE_REFRESH_TOKEN; if (!accessToken || !refreshToken) { throw new Error("OAuth2 tokens missing. Run oauth-setup.js to get tokens."); } oauth2Client.setCredentials({ access_token: accessToken, refresh_token: refreshToken, }); return oauth2Client; }

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/ricleedo/Google-Service-MCP'

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