如何使用JavaScript获取Outlook邮件真实Message ID以调用Microsoft Graph API
从Outlook网页端获取可用于Microsoft Graph API的真实Message ID方法
你从URL路径中提取到的ID是Outlook网页端自用的编码ID,和Microsoft Graph API要求的消息ID格式不兼容,因此无法直接调用接口,以下是两种JavaScript实现的可行方案:
方案1:Outlook Web插件开发场景(官方推荐)
如果你是基于Office.js开发Outlook Web插件,可以直接调用官方API获取兼容Graph的消息ID:
// 仅在Outlook Web Add-in运行环境下可用 if (Office.context.mailbox.item) { // 获取当前邮件的原始ID const rawItemId = Office.context.mailbox.item.itemId; // 转换为Microsoft Graph API兼容的ID格式(推荐执行) const graphUsableId = Office.context.mailbox.convertToRestId( rawItemId, Office.MailboxEnums.RestVersion.v1_0 ); // 直接使用graphUsableId调用Graph接口即可 console.log("Graph可用消息ID:", graphUsableId); }
方案2:非插件场景(自定义浏览器脚本/第三方集成)
如果你是在普通浏览器上下文运行代码(比如油猴脚本、自定义爬虫),可以先提取URL中的OWA格式ID,再调用Graph的ID转换接口转换为可用格式:
// 步骤1:从当前页面URL提取原始OWA ID const pathSegments = window.location.pathname.split('/'); const urlEncodedOwaId = pathSegments[pathSegments.length - 1]; const rawOwaId = decodeURIComponent(urlEncodedOwaId); // 步骤2:调用Graph转换接口,将OWA ID转为Graph可用格式 async function convertOwaIdToGraphId(owaId, graphAccessToken) { const response = await fetch("https://graph.microsoft.com/v1.0/me/translateExchangeIds", { method: "POST", headers: { "Authorization": `Bearer ${graphAccessToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ inputIds: [owaId], sourceIdType: "OwaId", targetIdType: "RestId" }) }); const result = await response.json(); return result.value[0].targetId; } // 调用示例,需传入已获取的、拥有Mail.Read权限的Graph访问令牌 const graphMsgId = await convertOwaIdToGraphId(rawOwaId, "你的Graph访问令牌");
后续调用说明
拿到转换后的ID后,直接调用单邮件查询接口即可获取完整邮件数据,接口支持自定义查询参数筛选返回字段、获取附件、获取互联网邮件ID等操作。
内容的提问来源于stack exchange,提问作者codingmaster398
相关产品推荐
相关产品推荐

