Google Apps 脚本 doPost 图像对象为空

问题描述 投票:0回答:1

我在通用 Google 帐户上部署了一个 Web 应用程序,我希望用作自动化项目的邮件服务器。 它运行良好,但我无法获取 inlineImages 对象来传递 POST 请求。图像对象总是空的。有人可以解释一下发生了什么以及是否有一种方法可以通过 POST 请求携带图像以包含(内联)在电子邮件中,以便与像这样的 GAS Web 应用程序一起使用?

服务器代码(简化):

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

  console.log(images) // Always outputs {'img_map: {}}

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

客户端代码:

// DriveApp.getFiles()
function myPost() {
  const map = DriveApp.getFileById(MYFILE_ID).getAs('image/png');
  const postData = {
    'apikey': APIKEY,
    'recipient': '[email protected]',
    'subject': 'Testing GAS mail server',
    'body': '<h1>Hello, Mail World!</h1><img src="cid:img_map"/>',
    'images': {'img_map': map}
  };
  var options = {
    'method' : 'POST',
    'payload' : JSON.stringify(postData),
    'headers': { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
    'muteHttpExceptions': true
  };
  const response = UrlFetchApp.fetch(MAIL_ENDPOINT, options);
  console.log(response.getResponseCode());
  console.log(response.getContentText());
}
google-apps-script post inline-images
1个回答
0
投票

我相信您的目标如下。

  • 您想要从功能
    myPost
    doPost
    发出请求。
    MAIL_ENDPOINT
    的值是
    doPost
    的 Web 应用程序 URL。
  • 您已经可以使用您的
    doPost
    myPost
    发出请求,但
    images
    的值未正确发送。

既然如此,下面的修改如何?在此修改中,图像文件作为 base64 数据发送。修改后的脚本如下。

doPost

function doPost(e) {
  const data = JSON.parse(e.postData.contents);
  let { apikey, recipient, subject, body, images } = data;
  images = { img_map: Utilities.newBlob(Utilities.base64Decode(images.img_map), 'image/png') };

  console.log(images) // Always outputs {'img_map: {}}

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

myPost

function myPost() {
  const map = Utilities.base64Encode(DriveApp.getFileById(MYFILE_ID).getAs('image/png').getBytes());
  const postData = {
    'apikey': APIKEY,
    'recipient': '[email protected]',
    'subject': 'Testing GAS mail server',
    'body': '<h1>Hello, Mail World!</h1><img src="cid:img_map"/>',
    'images': { 'img_map': map }
  };
  var options = {
    'method': 'POST',
    'payload': JSON.stringify(postData),
    'headers': { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
    'muteHttpExceptions': true
  };
  const response = UrlFetchApp.fetch(MAIL_ENDPOINT, options);
  console.log(response.getResponseCode());
  console.log(response.getContentText());
}
  • 使用此修改后的脚本并运行
    myPost
    时,
    postData
    的值将发送到
    doPost
    。并且,在
    doPost
    处,图像文件从 Base64 数据解码并与
    inlineImages
    一起使用。

注:

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.