Google Apps脚本:将Gmail附件保存到Google云端硬盘

时间:2019-11-11 22:46:57

标签: javascript google-apps-script

我即将完成我的Google Apps脚本项目,该项目将分析一个简单的两行电子邮件,并将附件链接(附件保存到Google云端硬盘中)添加到Google表格中。

我一直坚持将电子邮件附件保存到Google云端硬盘。被注释掉的代码是无法正常工作的块。我从Save Gmail attachments on Google Drive中举了一个例子-但这似乎对我不起作用。

附上我的完整代码。

function parseEmailMessages() {

  var threads = GmailApp.search('label:test',0,100);
  var sheet = SpreadsheetApp.openById('<<SHEET ID>>');
  var folder = DriveApp.getFolderById('<<FOLDER ID>>');
  var testLabel = GmailApp.getUserLabelByName('test');
  var doneLabel = GmailApp.getUserLabelByName('finished');

  for (var i = 0; i < threads.length; i++) {
    var message = threads[i].getMessages();
    for (var j in message) {
      var content = message[j].getPlainBody();

      /*
      var attachments = threads[j].getAttachments();
      for (var k in attachments) {
      var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
        if (!isDefinedType) continue;
        var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
      }
      */

    }

    var [name, date] = content.split("\n");    

    function latestFile() {
      var gDriveFolder = DriveApp.getFolderById('<<FOLDER ID>>');
      var gDriveFile = gDriveFolder.getFiles();
      var lastFileId = gDriveFile.next().getId(); 
      return lastFileId.toString();
    }

    var urlStart = 'https://drive.google.com/a/<<DOMAIN>>/file/d/';
    var urlString = latestFile();
    var urlEnd = '/view?usp=drivesdk';    
    var pic = urlStart + urlString + urlEnd;

    sheet.appendRow([name,date,pic]);

    threads[i].removeLabel(testLabel);
    threads[i].addLabel(doneLabel);

  }
}

我收到的错误是:“ TypeError:在对象GmailThread中找不到函数getAttachments。”

的确,文档中的getAttachments似乎不是GmailThread的一部分,但目前我不确定如何实现目标。

1 个答案:

答案 0 :(得分:1)

getAttachments()不是类GmailThread的方法。那么下面的修改如何?

发件人:

var attachments = threads[j].getAttachments();

收件人:

var attachments = message[j].getAttachments();

参考:

如果这不是直接解决方案,我深表歉意。