如何用Apps Script转发邮件并仅保留PDF附件(排除内联图片)
解决方案:仅转发PDF附件并移除内联图片,同时保持邮件线程
核心思路:利用GmailApp.sendEmail()的threadId参数保持线程
你之前认为无法使用sendEmail()是误解——该方法支持通过threadId参数将邮件发送到原线程中,完全满足你的需求。这种方式能让你完全控制转发的内容和附件,精准过滤掉内联图片。
具体实现代码
// 获取目标邮件及线程ID(替换为你实际获取邮件的逻辑) const lastMessage = GmailApp.search('label:你的目标标签')[0].getLastMessage(); const threadId = lastMessage.getThread().getId(); const forwardingAddress = "目标外部应用邮箱"; const fromAddress = "指定发件人邮箱"; const subject = lastMessage.getSubject(); // 可自定义主题内容 // 1. 筛选出仅PDF格式的附件 const pdfAttachments = lastMessage.getAttachments().filter(attachment => { const contentType = attachment.getContentType(); // 覆盖常见PDF MIME类型,避免遗漏 return contentType === 'application/pdf' || contentType === 'application/x-pdf'; }); // 2. 清理HTML内容,移除所有内联图片引用(带cid的img标签) const originalHtml = lastMessage.getBody(); // 正则匹配并移除所有关联内联附件的img标签 const cleanedHtml = originalHtml.replace(/<img[^>]*cid:[^>]*>/gi, '') + "<br> Message sent to external app <br>"; // 3. 清理纯文本内容(移除自动生成的[image]标记) const cleanedPlainText = lastMessage.getPlainBody().replace(/\[image\]/g, '') + "\n\nMessage sent to external app"; // 4. 发送邮件并关联到原线程 GmailApp.sendEmail( forwardingAddress, subject, cleanedPlainText, { from: fromAddress, htmlBody: cleanedHtml, attachments: pdfAttachments, threadId: threadId // 关键参数:确保邮件归入原线程 } );
关键步骤说明
- 附件过滤:通过检查附件的MIME类型,仅保留PDF格式文件,自动排除内联图片(内联图片的MIME类型通常为
image/png、image/jpeg等)。 - HTML清理:使用正则表达式移除所有引用内联图片的
<img>标签(这类标签包含cid:前缀,用于关联邮件中的内联附件资源)。 - 线程关联:通过
threadId参数,让新发送的邮件自动归入原邮件线程,完全符合你保持线程的需求。
替代方案:改进forward()方法的使用
如果你坚持使用forward(),可以尝试强制替换附件(部分场景下有效):
const pdfAttachments = lastMessage.getAttachments().filter(att => att.getContentType().includes('pdf')); const cleanedHtml = lastMessage.getBody().replace(/<img[^>]*cid:[^>]*>/gi, '') + "<br> Message sent to external app <br>"; lastMessage.forward(forwardingAddress, { from: fromAddress, subject: subject, htmlBody: cleanedHtml, attachments: pdfAttachments, noAttachments: true // 尝试排除原邮件所有附件,仅保留指定的PDF });
注:noAttachments参数并非所有环境都支持,如果无效,优先使用sendEmail()方案。
若上述方案仍有问题:使用Gmail API(高级方案)
如果需要更精准控制邮件结构,可以启用Gmail高级服务,直接修改邮件的payload部分,移除内联图片的parts后转发:
- 在Apps Script编辑器中,点击「服务」→「添加服务」→选择「Gmail API」并启用。
- 使用以下代码:
const messageId = lastMessage.getId(); const userId = "me"; // 获取原邮件完整结构信息 const message = Gmail.Users.Messages.get(userId, messageId, {format: 'full'}); // 过滤邮件内容部分,仅保留文本/HTML和PDF附件 const filteredParts = message.payload.parts.filter(part => { if (part.mimeType.includes('text/')) { return true; // 保留文本和HTML内容块 } // 仅保留标记为attachment的PDF,排除inline类型的内联图片 return part.filename?.endsWith('.pdf') && part.headers?.some(h => h.name === 'Content-Disposition' && h.value.includes('attachment')); }); // 发送转发请求 Gmail.Users.Messages.forward(userId, messageId, { requestBody: { payload: { parts: filteredParts, mimeType: message.payload.mimeType }, to: forwardingAddress, from: fromAddress, subject: subject } });
内容的提问来源于stack exchange,提问作者Arkadiusz Alicki
相关产品推荐
相关产品推荐

