如何基于Outlook JS API开发Web加载项实现邮件保存为.msg文件
实现Outlook Web加载项保存邮件为.msg文件的方案
Outlook JS API确实没有原生支持直接将邮件保存为.msg文件的功能,不过可以通过以下两种方案实现需求:
方案1:基于Exchange Web Services (EWS) 获取MIME内容并后端转换
步骤:
- 从加载项中获取当前邮件的
itemId和EWS服务地址 - 通过EWS的
GetItem请求获取邮件的MimeContent(Base64编码格式) - 将MIME内容发送到后端服务,使用第三方库将.eml格式转换为.msg格式
前端JS代码示例:
async function fetchMimeContentForMsgConversion() { const itemId = Office.context.mailbox.item.itemId; const ewsUrl = Office.context.mailbox.ewsUrl; const tokenResult = await Office.context.mailbox.getCallbackTokenAsync({ isRest: false }); const accessToken = tokenResult.value; // 构造EWS SOAP请求 const soapPayload = `<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <t:RequestServerVersion Version="Exchange2013_SP1" /> </soap:Header> <soap:Body> <m:GetItem> <m:ItemShape> <t:BaseShape>IdOnly</t:BaseShape> <t:AdditionalProperties> <t:FieldURI FieldURI="item:MimeContent" /> </t:AdditionalProperties> </m:ItemShape> <m:ItemIds> <t:ItemId Id="${itemId}" /> </m:ItemIds> </m:GetItem> </soap:Body> </soap:Envelope>`; try { const response = await fetch(ewsUrl, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'text/xml' }, body: soapPayload }); const xmlResp = await response.text(); // 解析XML提取Base64编码的MimeContent,发送到后端转换 const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlResp, "text/xml"); const mimeContentNode = xmlDoc.querySelector("t\\:MimeContent, MimeContent"); if (mimeContentNode) { const base64Mime = mimeContentNode.textContent; // 此处调用后端接口,传递base64Mime进行转换 } } catch (err) { console.error('获取MIME内容失败:', err); } }
方案2:使用Microsoft Graph API获取邮件内容并转换
步骤:
- 获取当前邮件的Graph兼容ID(可通过
Office.context.mailbox.item.restId或转换EWS ID得到) - 调用Graph API的
/me/messages/{id}/$value端点获取邮件的MIME流 - 后端使用邮件处理库(如MsgKit、Aspose.Email)将MIME内容转换为.msg文件
后端C#转换示例(使用MsgKit):
using MsgKit; using System.IO; using System.Net.Mail; public void ConvertEmlToMsg(byte[] emlBytes, string outputMsgPath) { using var emlStream = new MemoryStream(emlBytes); var mailMessage = new MailMessage(); mailMessage.Load(emlStream); using var msgStream = new FileStream(outputMsgPath, FileMode.Create); var outlookMsg = new Message( sender: mailMessage.From.Address, recipient: string.Join(";", mailMessage.To.Select(t => t.Address)), subject: mailMessage.Subject ); outlookMsg.BodyText = mailMessage.Body; // 处理邮件附件、抄送等其他属性 outlookMsg.Save(msgStream); }
关键注意事项:
- 前端无法直接生成.msg文件,必须依赖后端服务,因为.msg是Outlook专有二进制格式,需要特定库解析生成
- 确保加载项已申请足够的权限:EWS需要
ReadWriteMailbox权限,Graph API需要Mail.ReadWrite权限 - 测试时需覆盖不同Exchange Server版本和Outlook Web客户端环境
内容的提问来源于stack exchange,提问作者Pratik Ratanpara
相关产品推荐
相关产品推荐

