我在 Google Cloud Platform 上设置了第一个 Pub/Sub,它使用 Gmail API 在每次收到电子邮件时更新我的电子表格
(有关如何执行此操作的更多信息,请参阅我之前的问题) https://stackoverflow.com/questions/76790331/how-to-update-function-so-it-responds-to-certain-emails-automatically/76803573#76803573
但是,下面的 doPost 函数在我的电子表格上返回类似以下内容:
"2023 年 8 月 4 日 10:01:59"、"8011555761044464"、"{"电子邮件地址":"[电子邮件受保护] /cdn-cgi/l/email-protection","historyId":37309620}"
我还是个新手,但我希望电子表格包含发件人的信息和主题行。如何改进我的脚本?
// ************************* POST *************************
function doPost (e) {
const message = JSON.parse(e.postData.getDataAsString()).message;
const data = Utilities.newBlob(Utilities.base64Decode(message.data)).getDataAsString();
const ss = SpreadsheetApp.openById("MYSHEET").getSheetByName("Borghers Emails");
ss.appendRow([new Date(), message.message_id, data]);
return 200;
};
// ************************* ENROLL EMAIL *************************
function enrollEmail() {
try {
const watchRes = {
labelIds: ["INBOX"],
labelFilterAction: "include",
topicName: "projects/myproject/topics/gmailTrigger"
};
const response = Gmail.Users.watch(watchRes, "me");
console.log(response);
} catch (error) {
console.log(error);
}
};
编辑:这是更新的代码这确实有效,谢谢田池!但是,我认为 Pub/Sub 和我的脚本之间存在沟通不畅,因为当我发送一封测试电子邮件时,电子表格将进入无限循环,在该循环中更新工作表并且不会停止。我不确定如何与 Pub/Sub 通信以确保一次只发生一条消息。请参阅下面的我的脚本和工作表上的结果:
function doPost(e) {
const message = JSON.parse(e.postData.getDataAsString()).message;
const data = JSON.parse(Utilities.newBlob(Utilities.base64Decode(message.data)).getDataAsString());
const { historyId } = data;
const { history } = Gmail.Users.History.list("me", { startHistoryId: historyId });
if (history.length > 0) {
const messageId = history[0].messages[0].id;
const msg = GmailApp.getMessageById(messageId);
const ss = SpreadsheetApp.openById("MYSHEET").getSheetByName("Email Log");
ss.appendRow([new Date(), messageId, msg.getFrom(), msg.getSubject()]);
}
return ContentService.createTextOutput("ok");
}