Skip to main content
Glama

get_email_by_id

Retrieve a specific email by its unique ID from the Outlook MCP Server, enabling direct access to targeted messages for reading or processing.

Instructions

Get specific email by ID

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idYesEmail ID

Implementation Reference

  • Core handler function that retrieves a specific email by its EntryID using Outlook COM interop via PowerShell. Handles fallback search in Inbox/Sent/Drafts, extracts properties, base64-encodes body for safe JSON transport, and decodes on return.
    async getEmailById(id) { const script = ` try { Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook" -ErrorAction Stop $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop $namespace = $outlook.GetNamespace("MAPI") # Try to get the email by EntryID directly $item = $null try { $item = $namespace.GetItemFromID("${id.replace(/"/g, '""')}") } catch { # If direct retrieval fails, search in common folders $folders = @( $namespace.GetDefaultFolder(6), # Inbox $namespace.GetDefaultFolder(5), # Sent Items $namespace.GetDefaultFolder(16) # Drafts ) foreach ($folder in $folders) { try { foreach ($email in $folder.Items) { if ($email.EntryID -eq "${id.replace(/"/g, '""')}") { $item = $email break } } if ($item) { break } } catch { # Continue searching in other folders continue } } } if (-not $item) { throw "Email with ID '${id.replace(/"/g, '""')}' not found in any folder" } # Get email properties with better error handling $rawSubject = try { if ($item.Subject) { $item.Subject.ToString() } else { "No Subject" } } catch { "No Subject" } $rawSender = try { if ($item.SenderEmailAddress) { $item.SenderEmailAddress.ToString() } elseif ($item.SenderName) { $item.SenderName.ToString() } else { "Unknown Sender" } } catch { "Unknown Sender" } $rawBody = try { if ($item.Body) { $item.Body.ToString() } else { "No body content" } } catch { "Could not retrieve body content" } # Get recipients safely $recipients = @() try { if ($item.Recipients -and $item.Recipients.Count -gt 0) { foreach ($recipient in $item.Recipients) { try { if ($recipient.Address) { $recipients += $recipient.Address.ToString() } elseif ($recipient.Name) { $recipients += $recipient.Name.ToString() } } catch { # Skip problematic recipients continue } } } } catch { # Recipients collection might be inaccessible $recipients = @() } # Get timestamp $timestamp = try { if ($item.ReceivedTime) { $item.ReceivedTime.ToString("yyyy-MM-dd HH:mm:ss") } elseif ($item.SentOn) { $item.SentOn.ToString("yyyy-MM-dd HH:mm:ss") } elseif ($item.CreationTime) { $item.CreationTime.ToString("yyyy-MM-dd HH:mm:ss") } else { (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") } } catch { (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") } # Get read status $isRead = try { -not $item.UnRead } catch { $true } # Get attachments status $hasAttachments = try { $item.Attachments.Count -gt 0 } catch { $false } # Clean subject and sender for JSON safety, but preserve body formatting $cleanSubject = $rawSubject -replace '"', '""' -replace '\\', '\\\\' $cleanSender = $rawSender -replace '"', '""' -replace '\\', '\\\\' # Base64 encode body to avoid JSON parsing issues with special characters $bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($rawBody) $encodedBody = [System.Convert]::ToBase64String($bodyBytes) # Create email object with encoded body $email = [PSCustomObject]@{ Id = "${id.replace(/"/g, '""')}" Subject = $cleanSubject Sender = $cleanSender Recipients = $recipients Body = $encodedBody IsBodyEncoded = $true ReceivedTime = $timestamp IsRead = $isRead HasAttachments = $hasAttachments } # Output as JSON $jsonOutput = $email | ConvertTo-Json -Depth 4 -Compress Write-Output $jsonOutput } catch { # Create error response $errorResponse = [PSCustomObject]@{ Id = "${id.replace(/"/g, '""')}" Subject = "Error retrieving email" Sender = "system" Recipients = @() Body = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("Error: $($_.Exception.Message)")) IsBodyEncoded = $true ReceivedTime = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") IsRead = $true HasAttachments = $false Error = $_.Exception.Message } $errorJson = $errorResponse | ConvertTo-Json -Depth 4 -Compress Write-Output $errorJson } `; try { const result = await this.executePowerShell(script); if (!result || result.trim() === '') { throw new Error('PowerShell returned empty result'); } // Clean the result before parsing const cleanResult = result .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '') .trim(); const emailData = JSON.parse(cleanResult); // Decode the body if it's base64 encoded let bodyText = ''; if (emailData.IsBodyEncoded && emailData.Body) { try { const bodyBytes = Buffer.from(emailData.Body, 'base64'); bodyText = bodyBytes.toString('utf8'); } catch (decodeError) { bodyText = 'Could not decode email body'; } } else { bodyText = emailData.Body || ''; } return { id: emailData.Id || id, subject: emailData.Subject || 'No Subject', sender: emailData.Sender || 'Unknown Sender', recipients: Array.isArray(emailData.Recipients) ? emailData.Recipients : [], body: bodyText, receivedTime: new Date(emailData.ReceivedTime || new Date()), isRead: Boolean(emailData.IsRead), hasAttachments: Boolean(emailData.HasAttachments) }; } catch (parseError) { // If JSON parsing fails, return a fallback response return { id: id, subject: 'Email parsing failed', sender: 'system', recipients: [], body: `Failed to parse email data: ${parseError instanceof Error ? parseError.message : String(parseError)}`, receivedTime: new Date(), isRead: true, hasAttachments: false }; } }
  • MCP server tool dispatch handler for 'get_email_by_id'. Validates input ID, calls OutlookManager.getEmailById, and returns the full email object as formatted JSON text content.
    case 'get_email_by_id': { const id = (args as any)?.id; if (!id) { throw new Error('Email ID is required'); } const email = await outlookManager.getEmailById(id); return { content: [ { type: 'text', text: JSON.stringify(email, null, 2), }, ], }; }
  • Tool schema definition listing 'get_email_by_id' with required 'id' string input and description.
    { name: "get_email_by_id", description: "Get specific email by ID", inputSchema: { type: "object", properties: { id: { type: "string", description: "Email ID" } }, required: ["id"] } },
  • src/index.ts:26-458 (registration)
    Registration of all available tools via ListToolsRequestSchema handler, which statically lists 'get_email_by_id' among others.
    server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "get_inbox_emails", description: "Get inbox email list", inputSchema: { type: "object", properties: { count: { type: "number", description: "Number of emails to retrieve", default: 10 } } } }, { name: "get_email_by_id", description: "Get specific email by ID", inputSchema: { type: "object", properties: { id: { type: "string", description: "Email ID" } }, required: ["id"] } }, { name: "summarize_email", description: "Summarize individual email content", inputSchema: { type: "object", properties: { email_id: { type: "string", description: "Email ID to summarize" } }, required: ["email_id"] } }, { name: "summarize_inbox", description: "Summarize inbox emails", inputSchema: { type: "object", properties: { count: { type: "number", description: "Number of emails to summarize", default: 10 } } } }, { name: "create_draft", description: "Create new email draft", inputSchema: { type: "object", properties: { to: { type: "array", items: { type: "string" }, description: "Recipient email addresses" }, subject: { type: "string", description: "Email subject" }, body: { type: "string", description: "Email content" }, cc: { type: "array", items: { type: "string" }, description: "CC email addresses" }, bcc: { type: "array", items: { type: "string" }, description: "BCC email addresses" } }, required: ["to", "subject", "body"] } }, { name: "mark_email_as_read", description: "Mark email as read", inputSchema: { type: "object", properties: { email_id: { type: "string", description: "Email ID" } }, required: ["email_id"] } }, { name: "search_inbox_emails", description: "Search inbox emails", inputSchema: { type: "object", properties: { query: { type: "string", description: "Search keywords" }, count: { type: "number", description: "Number of results to return", default: 10 } }, required: ["query"] } }, { name: "search_sent_emails", description: "Search sent emails", inputSchema: { type: "object", properties: { query: { type: "string", description: "Search keywords" }, count: { type: "number", description: "Number of results to return", default: 10 } }, required: ["query"] } }, { name: "get_sent_emails", description: "Get sent emails list", inputSchema: { type: "object", properties: { count: { type: "number", description: "Number of sent emails to retrieve", default: 10 } } } }, { name: "get_draft_emails", description: "Get draft emails list", inputSchema: { type: "object", properties: { count: { type: "number", description: "Number of draft emails to retrieve", default: 10 } } } }, { name: "search_draft_emails", description: "Search draft emails", inputSchema: { type: "object", properties: { query: { type: "string", description: "Search keywords" }, count: { type: "number", description: "Number of results to return", default: 10 } }, required: ["query"] } }, { name: "duplicate_email_as_draft", description: "Duplicate existing email as draft (preserving complete format)", inputSchema: { type: "object", properties: { source_email_id: { type: "string", description: "Original email ID to duplicate" }, store_id: { type: "string", description: "Store ID for the original email (optional but recommended)" }, new_subject: { type: "string", description: "New email subject (optional)" }, new_recipients: { type: "array", items: { type: "string" }, description: "New recipient list (optional)" } }, required: ["source_email_id"] } }, { name: "set_show_as", description: "Set Show As (Free/Busy status) for a calendar event", inputSchema: { type: "object", properties: { eventId: { type: "string", description: "Event ID to update" }, subject: { type: "string", description: "Subject of the event to find" }, startDate: { type: "string", description: "Start date of the event to find (ISO 8601 format)" }, showAs: { type: "string", enum: ["Free", "Tentative", "Busy", "OutOfOffice", "WorkingElsewhere"], description: "Show As status to set" } }, required: ["showAs"] } }, { name: "create_event_with_show_as", description: "Create a calendar event with specific Show As status (e.g., OutOfOffice for vacation)", inputSchema: { type: "object", properties: { subject: { type: "string", description: "Event subject/title" }, start: { type: "string", description: "Start date and time (ISO 8601 format)" }, end: { type: "string", description: "End date and time (ISO 8601 format)" }, location: { type: "string", description: "Event location" }, body: { type: "string", description: "Event description/body" }, showAs: { type: "string", enum: ["Free", "Tentative", "Busy", "OutOfOffice", "WorkingElsewhere"], description: "Show As status (default: Busy)" }, reminderMinutes: { type: "number", description: "Reminder time in minutes before the event" } }, required: ["subject", "start", "end"] } }, { name: "list_events", description: "List calendar events within a specified date range", inputSchema: { type: "object", properties: { startDate: { type: "string", description: "Start date (ISO 8601 format)" }, endDate: { type: "string", description: "End date (ISO 8601 format, optional)" }, calendar: { type: "string", description: "Calendar name (optional)" } }, required: ["startDate"] } }, { name: "update_event", description: "Update an existing calendar event", inputSchema: { type: "object", properties: { eventId: { type: "string", description: "Event ID to update" }, subject: { type: "string", description: "New event subject/title (optional)" }, startDate: { type: "string", description: "New start date in MM/DD/YYYY format (optional)" }, startTime: { type: "string", description: "New start time in HH:MM AM/PM format (optional)" }, endDate: { type: "string", description: "New end date in MM/DD/YYYY format (optional)" }, endTime: { type: "string", description: "New end time in HH:MM AM/PM format (optional)" }, location: { type: "string", description: "New event location (optional)" }, body: { type: "string", description: "New event description/body (optional)" }, calendar: { type: "string", description: "Calendar name (optional)" } }, required: ["eventId"] } }, { name: "delete_event", description: "Delete a calendar event by its ID", inputSchema: { type: "object", properties: { eventId: { type: "string", description: "Event ID to delete" }, calendar: { type: "string", description: "Calendar name (optional)" } }, required: ["eventId"] } }, { name: "find_free_slots", description: "Find available time slots in the calendar", inputSchema: { type: "object", properties: { startDate: { type: "string", description: "Start date (ISO 8601 format)" }, endDate: { type: "string", description: "End date (ISO 8601 format, optional, defaults to 7 days from start)" }, duration: { type: "number", description: "Duration in minutes (optional, defaults to 30)" }, workDayStart: { type: "number", description: "Work day start hour (0-23) (optional, defaults to 9)" }, workDayEnd: { type: "number", description: "Work day end hour (0-23) (optional, defaults to 17)" }, calendar: { type: "string", description: "Calendar name (optional)" } }, required: ["startDate"] } }, { name: "get_attendee_status", description: "Check the response status of meeting attendees", inputSchema: { type: "object", properties: { eventId: { type: "string", description: "Event ID" }, calendar: { type: "string", description: "Calendar name (optional)" } }, required: ["eventId"] } }, { name: "get_calendars", description: "List available calendars", inputSchema: { type: "object", properties: {} } } ] }; });
  • Helper usage of getEmailById within duplicateEmailAsDraft method.
    const originalEmail = await this.getEmailById(sourceEmailId);

Other Tools

Related 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/cqyefeng119/windows-outlook-mcp'

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