Google Apps 脚本上的附件

问题描述

当我在 Google Apps 脚本中放入多个附件以通过电子邮件发送时遇到了一些问题。

执行此操作的代码部分是

      reportPDF = doc.getAs('application/pdf')
      reportPDF.setName('Attachment1 - '+ rows[0][0] + ".pdf");
      
      var file1 = destinationFolder.createFile(reportPDF);  
      var file2 = DriveApp.getFilesByName("test.pdf");

      DriveApp.getFileById(doc.getId()).setTrashed(true);
      
      emails.forEach(function(email) {
      MailApp.sendEmail(email,"Attachments  - " + rows[0][0],"Hello!",{
                        name: 'Good Practices',attachments: [file.getAs(MimeType.PDF),file2]

    });

但是当我运行这个时,我遇到了这个问题:

异常:无效参数:附件(第 151 行,文件 “电子邮件”)

我有一个 .doc 文件 1 已填充然后转换为 PDF 和另一个已经是 PDF 的文件 2。

当我只使用 file1 运行时,我可以发送电子邮件,但是当我尝试使用 file1 和 file2 时,出现此错误。谁能知道会发生什么?

我在堆栈中阅读了很多其他建议,但没有一个是有效的。

解决方法

说明:

问题是 file2 不是类型的 FILE 而是 FileIterator 类的对象。

另一方面,file1 属于 FILE 类型,这就是它正常工作的原因。

在发送电子邮件之前检查文件名是否存在也是一个好习惯。

解决方案:

function myFunction() {
  
  reportPDF = doc.getAs('application/pdf')
  reportPDF.setName('Attachment1 - '+ rows[0][0] + ".pdf");

  var file1 = destinationFolder.createFile(reportPDF);  // this is a file
  var folder = DriveApp.getFolderById(folderId); // put here the id of the folder
  var file2 = folder.getFilesByName("test.pdf"); // this is a file iterator

  DriveApp.getFileById(doc.getId()).setTrashed(true);
  
  if (file2.hasNext() ) {
      MailApp.sendEmail(emailAddress,"Attachments  - " + rows[0][0],"Hello!",{
      name: 'Good Practices',attachments: 
          [
           file1.getAs(MimeType.PDF),file2.next().getAs(MimeType.PDF)
          ]    
  })};  
}

参考: