我在通用 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());
}
我相信您的目标如下。
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
一起使用。在此修改中,假设
MYFILE_ID
、APIKEY
和MAIL_ENDPOINT
的变量已在其他地方声明,并且这些值是有效值。请注意这一点。
当您修改Web Apps的Google Apps脚本时,请将部署修改为新版本。这样,修改后的脚本就会反映在Web Apps中。请注意这一点。
您可以在我的报告“重新部署 Web 应用程序而不更改新 IDE 的 Web 应用程序的 URL(作者:我)”中查看详细信息。