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

Apps Script发送邮件仅支持PDF附件,如何设置支持图片附件?

解决方案

你当前代码仅能发送PDF附件的核心原因是attachments配置项强制对源文件做了PDF转码:file.getAs(MimeType.PDF)会把所有类型的源文件统一转换为PDF格式作为附件输出。

修改方案

1. 支持表格中存储的任意格式文件(含图片)作为附件

将attachments中强制转PDF的逻辑替换为直接读取源文件二进制内容即可,getBlob()方法会自动保留源文件的原始格式、MIME类型和文件名,PDF、JPG、PNG、GIF等常见格式都可正常识别发送:

// 仅修改这一行即可,把 getAs(MimeType.PDF) 替换为 getBlob()
attachments: [file.getBlob()],

2. 额外将正文中内嵌的两张图片也作为独立附件发送

如果需要把代码中预先定义的picture1、picture2(目前仅内嵌在邮件正文展示)也作为独立附件供收件人下载,直接把两个图片的blob对象加入attachments数组即可:

attachments: [file.getBlob(), picture1.getBlob(), picture2.getBlob()],

调整后完整可运行代码

function sendEmails() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('BD');
  const numRows = sh.getLastRow();
  const pdf = sh.getRange(numRows, 21).getValue();
  const fileid = pdf.slice(33, 66); // 截取Drive文件链接中的ID
  const file = DriveApp.getFileById(fileid)

  const id_img_1 = '1flyOEuH1WWYCrQF91feRPIdvjsFh-YfX'
  const id_img_2 = '1S3p6maECfBiF3J0PnOVfZ64YRxHj00On'
  const picture1 = DriveApp.getFileById(id_img_1); 
  const picture2 = DriveApp.getFileById(id_img_2);
  const inlineImages = {};
  inlineImages[picture1.getId()] = picture1.getBlob();
  inlineImages[picture2.getId()] = picture2.getBlob();
  let my_id = numRows - 1;

  sh.getRange(numRows, 1).setValue(my_id)    
  const email = sh.getRange(numRows, 2).getValue();

  MailApp.sendEmail({
    to: email,
    subject: "test",
    // 这里如果不需要把两张内嵌图作为附件,就去掉后面两个元素,只保留file.getBlob()即可
    attachments: [file.getBlob(), picture1.getBlob(), picture2.getBlob()],
    body: "Test message",
    htmlBody:'<img src="cid:' + picture1.getId() + '" />' +
             "<br/>\n"+
             "<br/>\n"+
             '<img src="cid:' + picture2.getId() + '" />' +
             "<br/>\n",
    inlineImages: inlineImages
  });
}

注:代码中额外清理了你原来HTML部分多余的</pre>标签,避免出现异常格式。


内容的提问来源于stack exchange,提问作者Alvim Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:36:03