我是应用程序脚本的新手,我正在尝试从收件箱中读取电子邮件。我认为 getThreads 可以完成这项工作,但我仍然不完全理解如何使用它。当我尝试执行下面编写的代码时,出现空错误。
查看documentation of getThreads()
,他们使用示例:
// Log the subject lines of the threads labeled with MyLabel
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
Logger.log(threads[i].getFirstMessageSubject());
}
“MyLabel”代表什么?
这是我尝试失败的代码
function myFunction() {
var label = GmailApp.getUserLabelByName('bobtheman@gmail.com');
var threads = label.getThreads();
for (var t in threads) {
var thread = threads[t];
// Gets the message body
var message = thread.getMessages()[0].getPlainBody();
}
GmailApp.sendEmail('barbrabat@gmail.com', 'hola', message)
}
最佳答案
MyLabel 是电子邮件的标签。这取决于您是否为特定电子邮件添加了标签。您可以使用搜索方法。
function myFunction(){
var label = 'yourLabel'; // if no label, remove the label in search
// it would be better if you add a label to a specific email for fast and more precise searching
var searchEmail = GmailApp.search('from:me subject:"' + subject + '" label:' + label + '');
var threadId = searchEmail[0].getId(); // get the id of the search email
var thread = GmailApp.getThreadById(threadId); // get email thread using the threadId
var emailMsg = thread.getMessages()[0]; // get the content of the email
var emailContent = emailMsg.getPlainBody(); // get the body of the email
// check using log
Logger.log(emailContent);
// how to open log
// Ctrl + Enter
// Run this function before checking the log
}
谢谢
关于javascript - 尝试理解 GAS 中的 getThreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48479463/