【问题标题】:how to get only today emails - Gmail + Google Script如何仅获取今天的电子邮件 - Gmail + Google 脚本
【发布时间】:2021-02-03 17:30:07
【问题描述】:

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

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

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

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

我更喜欢使用GmailApp.getUserLabelByName() 而不是Gmail.Users.Messages.list(),这样我就可以使用线程而不是消息。我正确理解这两种方法的工作原理。

【问题讨论】:

  • formatDate可以给日期加数字吗?
  • 更具体
  • O 需要在当前日期加上 2 来准备查询。由于日期,它不仅仅是简单的添加。 --- 看起来@Marios 回答了这个问题。

标签: javascript google-apps-script gmail-api


【解决方案1】:

解释:

  • 正如Cooper 所建议的那样,您可以构建日期和 使用Utilities 类将它们转换为所需的格式。

  • 然后,您可以使用Template literals 构造查询参数并将所有日期和标签变量传递给字符串对象。

  • 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
}

【讨论】:

  • 我不明白SpreadsheetApp.getActive() 是什么意思。我需要为计算创建一些临时电子表格还是...?
  • @Radek 检查我更新的答案。您可以用您自己的时区替换该部分。
  • 你是说搜索的结果是线程数组?那将完全回答我想在这里解决的问题。让我检查一下,然后我接受你的回答。谢谢。
  • @Radek 是的,它是一个线程数组。因此代码中的名称为threads
  • @Radek 你能再试一试吗,改用这个:const threads =GmailApp.search(queryString, 0, 10);。如果这也不起作用。请发布一个新问题,以便其他人可以提出建议。
猜你喜欢
  • 2015-02-28
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多