我正在尝试创建一个自动回复功能的脚本。我目前正试图抓住分配给特定标签的每个电子邮件,并抓住每个电子邮件的具体细节,但我收到一个错误陈述TypeError:线程。getMessages不是一个函数,尽管我已经三次检查了这确实是GMAIL脚本的一个函数。我在这段代码中做错了什么可能导致这个错误吗?
var labelName = "auto-reply-incoming";
var receivedCount = 0;
// extract emails from label in Gmail
function extractEmails() {
// get all email threads that match label
var receivedSearchQuery = "label:"+labelName+" -is:sent";
var threads = GmailApp.search(receivedSearchQuery, 0, 500);
for (var i=0; i<threads.length; i++) {
//count received emails in label
receivedCount = receivedCount + threads[i].getMessageCount();
//get body of each email
var message = threads.getMessages()[i].getBody();
//get recipient of each email
var recipient = threads.getMessages()[i].getTo();
}
Logger.log(receivedCount);
Logger.log(recipient);
}
出现问题是因为代码使用的线程迭代器可能大于某些线程上的消息数,更具体地说,问题在以下几行:
//get body of each email
var message = threads.getMessages()[i].getBody();
//get recipient of each email
var recipient = threads.getMessages()[i].getTo();
这是一个快速修复(用下面的替换上面的)
var messages = threads[i].getMessages();
for( j = 0; j < messages.length; j++){
//get body of each email
var message = messages[j].getBody();
//get recipient of each email
var recipient = messages[j].getTo();
}
注意:Logger.log(recipient)
将记录最后一个线程的最后一条消息的接收者。
试试这个:
function extractEmails() {
var labelName = "auto-reply-incoming";
var receivedCount = 0;
var receivedSearchQuery = "label:" + labelName + " -is:sent";
var ts = GmailApp.search(receivedSearchQuery, 0, 500);
var a = [];
ts.forEach((t, i) => {
let ms = t.getMessages();
ms.forEach((m, j) => {
let msg = m.getBody();
let rec = m.getTo();
a.push({ threadindex: j, messageindex: i, message: msg, recipient: rec })
});
});
Logger.log(JSON.stringify(a));
}