Outlook桌面端插件:解析邮件正文img src属性技术求助
解析Outlook桌面端插件中邮件正文的内嵌图片引用
邮件正文中的~WRS{GUID}.fld/xxx.jpg格式是Outlook对内嵌附件的特殊引用格式,下面是具体的解析和替换步骤:
步骤1:提取并解码图片引用中的附件GUID
从src属性中分离出URL编码的GUID部分,解码后得到附件的唯一标识:
function extractAttachmentGuid(imgSrc) { // 匹配%7b(...)%7d片段(%7b是{的URL编码,%7d是}的编码) const guidMatch = imgSrc.match(/%7b([0-9A-F-]+)%7d/); if (guidMatch?.[1]) { // 去掉{}符号,返回纯GUID字符串 return decodeURIComponent(guidMatch[0]).replace(/[{}]/g, ''); } return null; }
步骤2:根据GUID匹配对应的邮件附件
遍历当前邮件的附件列表,找到id属性与提取出的GUID一致的附件:
function findAttachmentByGuid(guid) { const attachments = Office.context.mailbox.item.attachments; return attachments.find(att => att.id === guid); }
步骤3:获取附件内容并替换图片引用
调用getAttachmentContentAsync获取附件的Base64内容,将原img的src替换为Data URI:
function replaceImageSrcWithDataUri(imgElement) { const imgSrc = imgElement.src; const guid = extractAttachmentGuid(imgSrc); if (!guid) return; const targetAttachment = findAttachmentByGuid(guid); if (!targetAttachment) return; Office.context.mailbox.item.getAttachmentContentAsync( targetAttachment.id, { asyncContext: imgElement }, function(result) { if (result.status === Office.AsyncResultStatus.Succeeded) { const base64Content = result.value.content; const contentType = targetAttachment.contentType; // 构建Data URI替换原src imgElement.src = `data:${contentType};base64,${base64Content}`; } else { console.error('获取附件内容失败:', result.error.message); } } ); }
完整流程示例
结合body.getAsync获取邮件正文后的处理逻辑:
// 获取邮件HTML格式正文 Office.context.mailbox.item.body.getAsync( Office.CoercionType.Html, function(result) { if (result.status === Office.AsyncResultStatus.Succeeded) { const bodyHtml = result.value; // 用临时DOM解析HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = bodyHtml; // 筛选所有WRS格式的图片 const wrsImgs = tempDiv.querySelectorAll('img[src^="~WRS"]'); // 逐个处理图片引用 wrsImgs.forEach(img => replaceImageSrcWithDataUri(img)); // 处理后的HTML可用于展示或后续操作 const processedHtml = tempDiv.innerHTML; console.log('处理完成的正文:', processedHtml); } else { console.error('获取邮件正文失败:', result.error.message); } } );
注意事项
- 仅适配Outlook桌面端:
~WRS格式是桌面端特有的内嵌附件引用规则,Web/移动端格式不同 - 权限要求:插件需在
manifest.xml中声明ReadItem及以上权限,否则无法访问附件内容 - 附件类型:上述代码针对图片附件优化,其他类型附件需调整Content-Type参数
内容的提问来源于stack exchange,提问作者Teeeeee
相关产品推荐
相关产品推荐

