Google Apps 脚本中的附件问题

Problem with Attachments in Google Apps Script

我有以下代码:

    reportPDF = doc.getAs('application/pdf')
    reportPDF.setName('Automated report - '+ rows[0][0] + ".pdf");
    
    var file1 = destinationFolder.createFile(reportPDF);  
    var folder = DriveApp.getFolderById("19Rv2f-Ud4Ncdzu-1MT1vUmh49pOKfKZX");
    var file2 = folder.getFilesByName("test.pdf");

    DriveApp.getFileById(doc.getId()).setTrashed(true);

    if(file2.hasNext()){
          emails.forEach(function(email) {
          MailApp.sendEmail(email, "Automated Report - " + rows[0][0], "Hello!", {
          name: 'Good Practices Report',
          attachments: 
            [
            file1.getAs(MimeType.PDF),
            file2.next().getAs(MimeType.PDF)
            ]

                                       });
                          })
      }

使用此代码,我应该会收到一封包含两个附件(file1 和 file2)的电子邮件。但是,当我 运行 它时,出现以下错误:

Exception: Cannot retrieve the next object: iterator has reached the end. (line 158, file "Email")

在这个文件夹中,我只有一个名为 test.pdf 的文件,但代码仍然在 第 158 行提示错误:file2.next().getAs(MimeType.PDF).

有人知道会发生什么吗?

修改点:

  • 我认为你的Cannot retrieve the next object: iterator has reached the end.问题的原因是循环中使用了file2.next()。在这种情况下,我认为在if(file2.hasNext()){之前是运行,迭代器可能已经结束了。

那么,当你想在attachments: 使用file1.getAs(MimeType.PDF)file2.next().getAs(MimeType.PDF)的文件时,还要从In this folder, I just have one file with the name test.pdf使用,下面的修改如何?

修改后的脚本:

请按如下方式修改您的脚本。

从:
if(file2.hasNext()){
  emails.forEach(function(email) {
    MailApp.sendEmail(email, "Automated Report - " + rows[0][0], "Hello!", {
      name: 'Good Practices Report',
      attachments: [
        file1.getAs(MimeType.PDF),
        file2.next().getAs(MimeType.PDF)
      ]
    });
  })
}
到:
if (file2.hasNext()) {
  var file2Pdf = file2.next().getAs(MimeType.PDF);  // Added
  emails.forEach(function(email) {
    MailApp.sendEmail(email, "Automated Report - " + rows[0][0], "Hello!", {
      name: 'Good Practices Report',
      attachments: [
        file1.getAs(MimeType.PDF),
        file2Pdf  // Modified
      ]
    });
  })
}
  • 在这个修改中,file1.getAs(MimeType.PDF)file2Pdf的文件在循环中被用作attachments

参考: