You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Gmail API与Google Apps Script替换/移除邮件附件?

在Google Apps Script中移除/替换Gmail邮件附件的解决方案

Gmail Apps Script原生服务没有提供直接移除或替换邮件附件的API,需要通过导出邮件核心内容、重新构建不含/含新附件的邮件的间接方式实现,以下是具体方案:

一、移除邮件附件

对于已发送的邮件,无法直接修改原邮件,只能在原线程中发送无附件的新版本,并归档原邮件避免混淆:

function removeAttachmentsFromMessage(messageId) {
  const message = GmailApp.getMessageById(messageId);
  const thread = message.getThread();
  
  // 提取邮件关键信息
  const subject = message.getSubject();
  const to = message.getTo();
  const cc = message.getCc();
  const bcc = message.getBcc();
  const htmlBody = message.getBody();
  const plainBody = message.getPlainBody();
  
  // 发送无附件的新邮件到原线程,保留线程关联
  const newMessage = thread.replyAll('', {
    subject: subject,
    htmlBody: htmlBody,
    plainBody: plainBody,
    cc: cc,
    bcc: bcc,
    headers: {
      'In-Reply-To': message.getId(),
      'References': message.getId()
    }
  });
  
  // 归档原邮件,减少视觉干扰
  message.moveToArchive();
  
  return newMessage.getId();
}

二、替换邮件附件

核心逻辑是提取原邮件内容,移除旧附件并添加新附件后重新发送到原线程:

function replaceAttachmentsInMessage(messageId, newAttachmentFiles) {
  const message = GmailApp.getMessageById(messageId);
  const thread = message.getThread();
  
  // 提取邮件关键信息
  const subject = message.getSubject();
  const to = message.getTo();
  const cc = message.getCc();
  const bcc = message.getBcc();
  const htmlBody = message.getBody();
  const plainBody = message.getPlainBody();
  
  // 发送带新附件的邮件到原线程
  const newMessage = thread.replyAll('', {
    subject: subject,
    htmlBody: htmlBody,
    plainBody: plainBody,
    cc: cc,
    bcc: bcc,
    attachments: newAttachmentFiles,
    headers: {
      'In-Reply-To': message.getId(),
      'References': message.getId()
    }
  });
  
  // 归档原邮件
  message.moveToArchive();
  
  return newMessage.getId();
}

// 使用示例:替换为Google Drive中的文件
function testReplaceAttachment() {
  const targetMessageId = '替换为你的邮件ID';
  const newAttachment = DriveApp.getFileById('替换为你的Drive文件ID');
  replaceAttachmentsInMessage(targetMessageId, [newAttachment]);
}

三、处理草稿邮件

如果是未发送的草稿,可以直接更新草稿的附件,无需重新发送:

function replaceDraftAttachments(draftId, newAttachmentFiles) {
  const draft = GmailApp.getDraft(draftId);
  const originalMessage = draft.getMessage();
  
  // 更新草稿内容,替换附件
  draft.update(
    originalMessage.getSubject(),
    originalMessage.getTo(),
    originalMessage.getBody(),
    {
      cc: originalMessage.getCc(),
      bcc: originalMessage.getBcc(),
      attachments: newAttachmentFiles
    }
  );
}

注意事项

  • Gmail不允许直接修改已发送的邮件,上述方案通过“新邮件替换原邮件”的方式实现需求,原邮件会被归档但不会被删除
  • 若需要保留原邮件的所有元数据(如发送时间),可以结合Gmail Advanced Service调用底层API,但实现复杂度会更高

内容的提问来源于stack exchange,提问作者Nikunj Sondagar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:31:17