按名称获取文件时,Google电子表格错误未发送文件

时间:2015-07-02 13:18:50

标签: javascript google-apps-script google-sheets

以下是我的以下代码,如果我将函数getFilesByName()更改为getFileById(),那么它的工作完全正常,有什么不同,为什么这不起作用呢?

Google Script Error

// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function sendEmails2() {

  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 4;   // Number of rows to process

  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 5)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();

  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var name = row[0];
    var emailAddress = row[1];  // First column
    var filename = DriveApp.getFilesByName(row[2]); // Second column
    var message = row[3];     // Third column
    var emailSent = row[4];  // Fourth column

    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "TEST" + name;
      MailApp.sendEmail(emailAddress, subject, message, {
          name: 'TEST',
          attachments: [filename.getAs(MimeType.PDF)]
      });
      sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }

  }
}

1 个答案:

答案 0 :(得分:1)

该错误实际上非常明确,您有一个File Iterator类(documentation)而不是File,您必须应用方法next()才能获得最新信息使用该名称更新的文件,如果您有更多具有该名称的文件,则可以在循环中使用hasNext()next()的组合。