更新时间:2023-12-05 14:21:46
我认为您正在寻找GmailApp.getMessagesForThreads().
I think you are looking for GmailApp.getMessagesForThreads().
function fetchEmails(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var threads = GmailApp.search('label:searchedLabel');
var messages = new Array();
function Email(message){
this.date = new Date(message.getDate());
this.body = message.getBody();
}
var gmailMessages = GmailApp.getMessagesForThreads(threads);
for(var i=0;i<thread.length;i++){
var messagesForThread = gmailMessages[i];
for(var j=0;j<messagesForThread.length;j++){
if(messagesForThread[j].getFrom()=="firstName lastName <email@domain.com>"){
var message = new Email(messagesForThread[j]);
messages.push(message);
}
}
}
}
当然,您也可以写得更简洁一些(对不起,我无法提供一个机会来学习JavaScript的奇妙之处):
Of course you can also write this a little more concisely (sorry, I can't turn up an opportunity to educate about the wonders of JavaScript):
function fetchEmails(){
var messages = Array.prototype.concat.apply([], GmailApp.getMessagesForThreads(
GmailApp.search('label:searchedLabel')).map(function(messagesForThread) {
return messagesForThread.filter(function(message) {
return message.getFrom() == "firstName lastName <email@domain.com>";
}).map(function(message) {
return { date: new Date(message.getDate()), body: message.getBody() };
});}));
}
这总共对Gmail进行了2次通话,因此速度很快.
This makes a grand total of 2 calls to Gmail, so it's going to be fast.
实际上,如果您按照上面的建议将"from"部分集成到搜索中,则只需要:
In fact, if you integrate the 'from' part into the search as was suggested above, all you need is:
function fetchEmails(){
var messages = Array.prototype.concat.apply([], GmailApp.getMessagesForThreads(
GmailApp.search('label:searchedLabel from:email@domain.com')).map(
function(messagesForThread) {
return messagesForThread.map(function(message) {
return { date: new Date(message.getDate()), body: message.getBody() };
});}));
}
最后,由于您实际上并不关心线程的结构,因此您可以在映射之前将数组连接起来,从而导致:
Finally, since you don't actually care about the thread structure, you can just concat the arrays before the map, which leads to this:
function fetchEmails(){
var messages = GmailApp.getMessagesForThreads(
GmailApp.search('label:searchedLabel from:email@domain.com'))
.reduce(function(a, b){ return a.concat(b); })
.map(function(message) {
return { date: new Date(message.getDate()), body: message.getBody() };
});
}
(我留在较早的示例中,以防您确实关心线程结构,而您只是给出一个最小的示例).
(I left in the earlier samples in case you do care about the thread structure and you were just giving a minimal example).