如何使用GmailApi获取文件 - AppScript

时间:2017-10-04 14:39:00

标签: google-apps-script gmail

我想用脚本获取我的电子邮件文件,我可以获得大小,名称等,但我可以下载或复制到我的驱动器这些文件?

 function TestFils(){
var threads = GmailApp.getInboxThreads(0, 20);
var msgs = GmailApp.getMessagesForThreads(threads);
for (var i = 0 ; i < msgs.length; i++) {
  for (var j = 0; j < msgs[i].length; j++) {
    var attachments = msgs[i][j].getAttachments();
    for (var k = 0; k < attachments.length; k++) {
      Logger.log('Message "%s" contains the attachment "%s" (%s bytes)',
                 msgs[i][j].getSubject(), attachments[k].getName(), attachments[k].getSize());
      if (attachments[k].getName().match(/.jpg*/))
           attachments[k].getAs("image/jpeg");
    }
  }
}

}

1 个答案:

答案 0 :(得分:0)

在您的脚本中,attachments是文件blob。因此,您可以使用文件blob将其下载到Google云端硬盘。修改后的脚本如下。

修改后的脚本:

function TestFils(){
  var threads = GmailApp.getInboxThreads(0, 20);
  var msgs = GmailApp.getMessagesForThreads(threads);
  for (var i = 0 ; i < msgs.length; i++) {
    for (var j = 0; j < msgs[i].length; j++) {
      var attachments = msgs[i][j].getAttachments();
      for (var k = 0; k < attachments.length; k++) {
        Logger.log('Message "%s" contains the attachment "%s" (%s bytes)',
        msgs[i][j].getSubject(), attachments[k].getName(), attachments[k].getSize());
        if (attachments[k].getName().match(/.jpg*/)) {
          DriveApp.createFile(attachments[k]);
        }
      }
    }
  }
}

注意:

在此示例中,附件文件将下载到Google云端硬盘的根文件夹中。如果您要将文件下载到特定文件夹,请使用DriveApp.getFolderById(folderId).createFile(attachments[k]);代替DriveApp.createFile(attachments[k]);