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

Google Apps Script doPost中inlineImages对象为空问题求助

GAS Web App POST传递inlineImages为空的原因及解决方法

原因分析

核心问题是Blob对象无法被JSON序列化:客户端中DriveApp.getFileById().getAs('image/png')返回的是Blob类型数据,但JSON.stringify()处理Blob时会直接将其转为空对象{},导致服务器端接收到的images字段里的img_map始终是空的。

可行解决方法

通过将Blob转换为Base64字符串传递,服务器端再还原为Blob对象,就能正常传递嵌入邮件所需的图像数据。

修改后的客户端代码

function myPost() {
  // 将Blob转为Base64字符串
  const imageBlob = DriveApp.getFileById(MYFILE_ID).getAs('image/png');
  const base64Image = Utilities.base64Encode(imageBlob.getBytes());

  const postData = {
    'apikey': APIKEY,
    'recipient': 'me@example.com',
    'subject': 'Testing GAS mail server',
    'body': '<h1>Hello, Mail World!</h1><img src="cid:img_map"/>',
    'images': {'img_map': base64Image}
  };

  var options = {
    'method' : 'POST',
    'payload' : JSON.stringify(postData),
    'headers': { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
    'muteHttpExceptions': true,
    'contentType': 'application/json' // 明确指定内容类型,避免解析问题
  };

  const response = UrlFetchApp.fetch(MAIL_ENDPOINT, options);
  console.log(response.getResponseCode());
  console.log(response.getContentText());
}

修改后的服务器端代码

function doPost(e) {
  const data = JSON.parse(e.postData.contents);
  const { apikey, recipient, subject, body, images } = data;

  // 将Base64字符串还原为Blob对象
  const inlineImages = {};
  for (const key in images) {
    const bytes = Utilities.base64Decode(images[key]);
    inlineImages[key] = Utilities.newBlob(bytes, 'image/png', key);
  }

  MailApp.sendEmail(recipient, subject, "", {
    name: "TSL mail server", 
    htmlBody: body, 
    inlineImages: inlineImages
  });
  
  return ContentService.createTextOutput('Email sent successfully.');
}

补充说明

  • 客户端需添加contentType: 'application/json',确保服务器端能正确解析JSON格式的请求体;
  • 若传递多种类型的图像,可在postData中额外携带图像MIME类型,服务器端根据类型创建Blob,适配更复杂场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 17:25:33