如何仅获取今天的电子邮件 - Gmail + Google Script

在我的谷歌脚本中,我只想解析今天+带有特定标签的电子邮件。

  1. 使用 Gmail.Users.Messages.list() 的解决方案

我发现可能的解决方案是使用搜索查询。今天是20.10.2020,此搜索查询after:2020/10/20 before:2020/10/22 仅返回今天的电子邮件。如果我使用此解决方案,我不知道如何将正确的日期传递给查询。

  1. 使用 GmailApp.getUserLabelByName() 的解决方案

我宁愿使用GmailApp.getUserLabelByName()notGmail.Users.Messages.list()这样我就可以使用线程而不是消息。我正确地理解这两种方法是如何工作的。


汪汪一只猫
浏览 72回答 1
1回答

UYOU

解释:正如Cooper所建议的那样,您可以使用Utilities类构造日期并将它们转换为所需的格式。然后,您可以使用模板文字构造查询参数并将所有日期和标签变量传递给字符串对象。getSpreadsheetTimeZone()用于获取电子表格的时区。您可以将其替换为实际的GMT,例如:const td = Utilities.formatDate(today, 'GMT+1', "yyyy/MM/dd"); const td_2 = Utilities.formatDate(today_2, 'GMT+1', "yyyy/MM/dd");使用电子表格时区的解决方案:function myFunction() {  const ss = SpreadsheetApp.getActive();  const today = new Date();  const today_2 = new Date();  today_2.setDate(new Date().getDate()+2);  const td = Utilities.formatDate(today, ss.getSpreadsheetTimeZone(), "yyyy/MM/dd");  const td_2 = Utilities.formatDate(today_2, ss.getSpreadsheetTimeZone(), "yyyy/MM/dd");  const mylabel = 'unread';    const queryString = `label: ${mylabel} after: ${td} before: ${td_2}`;  const threads = GmailApp.search(queryString); }自定义时区的解决方案:调整GMT+1到您自己/想要的时区。function myFunction() {    const today = new Date();  const today_2 = new Date();  today_2.setDate(new Date().getDate()+2);  const td = Utilities.formatDate(today, 'GMT+1', "yyyy/MM/dd");  const td_2 = Utilities.formatDate(today_2, 'GMT+1', "yyyy/MM/dd");  const mylabel = 'unread';    const queryString = `label: ${mylabel} after: ${td} before: ${td_2}`;  Logger.log(queryString); // check the output in the View -> Logs  const threads = GmailApp.search(queryString); // GmailThread[] — an array of Gmail threads matching this query}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript