Skip to main content
Glama

get_email_by_id

Retrieve a specific email from Microsoft Outlook using its unique identifier to access message details directly.

Instructions

Get specific email by ID

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idYesEmail ID

Implementation Reference

  • Tool schema definition for get_email_by_id including name, description, and input schema requiring 'id' string
    {
      name: "get_email_by_id", 
      description: "Get specific email by ID",
      inputSchema: {
        type: "object",
        properties: {
          id: {
            type: "string",
            description: "Email ID"
          }
        },
        required: ["id"]
      }
    },
  • MCP server callTool handler: extracts 'id' from args, calls outlookManager.getEmailById, returns the email 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),
          },
        ],
      };
    }
  • OutlookManager.getEmailById helper method: Uses PowerShell COM interop with Outlook.Application to fetch email by EntryID, extracts properties (subject, sender, body, recipients, etc.), handles fallbacks and parsing errors.
    async getEmailById(id: string): Promise<EmailMessage> {
      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 GetItemFromID first (fastest method)
          $item = $null
          try {
            $item = $namespace.GetItemFromID("${id.replace(/"/g, '""')}")
          } catch {
            # Fallback: search through folders
            foreach ($folderNum in @(6, 5, 16)) {
              $folder = $namespace.GetDefaultFolder($folderNum)
              foreach ($email in $folder.Items) {
                if ($email.EntryID -eq "${id.replace(/"/g, '""')}") {
                  $item = $email
                  break
                }
              }
              if ($item) { break }
            }
          }
          
          if (-not $item) { throw "Email not found" }
          
          # Extract data
          $subject = if ($item.Subject) { $item.Subject } else { "No Subject" }
          $sender = if ($item.SenderEmailAddress) { $item.SenderEmailAddress } else { "Unknown" }
          $body = if ($item.Body) { $item.Body } else { "" }
          $recipients = @()
          if ($item.Recipients) {
            foreach ($r in $item.Recipients) {
              $addr = if ($r.Address) { $r.Address } else { $r.Name }
              if ($addr) { $recipients += $addr }
            }
          }
          $timestamp = if ($item.SentOn) { $item.SentOn.ToString("yyyy-MM-dd HH:mm:ss") } 
                       elseif ($item.ReceivedTime) { $item.ReceivedTime.ToString("yyyy-MM-dd HH:mm:ss") } 
                       else { (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") }
          
          Write-Output ([PSCustomObject]@{
            Id = "${id.replace(/"/g, '""')}"
            Subject = $subject
            Sender = $sender
            Recipients = $recipients
            Body = $body
            ReceivedTime = $timestamp
            IsRead = -not $item.UnRead
            HasAttachments = $item.Attachments.Count -gt 0
            Success = $true
          } | ConvertTo-Json -Depth 3 -Compress)
          
        } catch {
          Write-Output ([PSCustomObject]@{
            Id = "${id.replace(/"/g, '""')}"
            Subject = "Email not found"
            Sender = "system"
            Recipients = @()
            Body = "Error: $($_.Exception.Message)"
            ReceivedTime = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
            IsRead = $true
            HasAttachments = $false
            Success = $false
          } | ConvertTo-Json -Depth 3 -Compress)
        }
      `;
    
      try {
        const result = await this.executePowerShell(script);
        const cleanResult = result.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '').trim();
        const emailData = JSON.parse(cleanResult);
        
        return {
          id: emailData.Id || id,
          subject: this.cleanText(emailData.Subject || 'No Subject'),
          sender: this.cleanText(emailData.Sender || 'Unknown Sender'),
          recipients: Array.isArray(emailData.Recipients) ? emailData.Recipients.map((r: any) => this.cleanText(r)) : [],
          body: emailData.Body || '',
          receivedTime: new Date(emailData.ReceivedTime || new Date()),
          isRead: Boolean(emailData.IsRead),
          hasAttachments: Boolean(emailData.HasAttachments)
        };
        
      } catch (error) {
        return {
          id: id,
          subject: 'Email parsing failed',
          sender: 'system',
          recipients: [],
          body: `Failed to parse email: ${error instanceof Error ? error.message : String(error)}`,
          receivedTime: new Date(),
          isRead: true,
          hasAttachments: false
        };
      }
    }

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