首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Google脚本从Gmail获取附件

使用Google脚本从Gmail获取附件
EN

Stack Overflow用户
提问于 2017-09-29 23:52:07
回答 2查看 7.7K关注 0票数 1

因此,我构建了一个电子表格,从2个不同的来源获取2个报告,然后将它们导入到工作表中。其中一个报告是每小时发送到我的电子邮件的CSV文件。

我有works....mostly的脚本。它将检查我的电子邮件中的线程,提取邮件,然后将附件导入工作表。问题是,当下一个小时收到下一封电子邮件,脚本再次运行时,它不会提取最新的附件,它只会提取第一个附件。我甚至尝试过在每次运行时将消息移动到我的垃圾桶中,但它仍然会将其从垃圾桶中拉出。这是我的代码。

function importReport() {

  var threads = GmailApp.search('in:inbox from:"system@Report.com"');
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];
  attachment.setContentType('text/csv');

 // Is the attachment a CSV file
 if (attachment.getContentType() === "text/csv") {

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("RawReport");
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

  // Remember to clear the content of the sheet before importing new data
   sheet.clearContents().clearFormats();
   sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);

 GmailApp.moveMessageToTrash(message);
  }


}

它的目标是拉出整个线程,然后导入最新的附件,有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-30 00:00:00

您应该尝试从Gmail线程中提取最后一条消息,而不是第一条消息。

var messages = threads[0].getMessages();
var message = messages[messages.length - 1];
票数 3
EN

Stack Overflow用户

发布于 2017-09-30 01:10:32

因此,感谢用户@AmitAgarwal,修复如下。

//download the thread with all the attachments (they will build up over time)
   var message = threads[0].getMessages(); 
  //Get the most recent attachment
  var attachment = message[message.length - 1].getAttachments()[0];

这将下载整个线程,并获得最新的附件。

我想到的另一种解决方案是在拉出数组后反转它。

var message = threads[0].getMessages();
message.reverse();
var attachment = message[0].getAttachments()[0];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46492616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档