简体   繁体   中英

TypeError : is not a function in Google Apps Script (MailApp code)

I'm trying to send an email through Google Apps script, but I can't load the attachment.

The file name and variable appear to have been defined, but the following message appears, and the code does not execute.

TypeError: paymentPDF.getAs is not a function

How should I fix it?

function test() {
  
  var noteSheet = getSheetById(noteSheet id); 
  var paymentSheet = getSheetById(paymentSheet id); 

  var emailTitle = noteSheet.getRange(2,2).getValue();
  var emailContent = noteSheet.getRange(3,2).getValue();
  var emailRecipient = noteSheet.getRange(4,2).getValue();

  var fileName = paymentSheet.getRange(2,2).getValue();
  var paymentPDF = DriveApp.getFilesByName(fileName);

  var file = DriveApp.getFileById("file id");
  MailApp.sendEmail(emailRecipient, emailTitle, emailContent, {
      name: 'test name',
      attachments: [paymentPDF.getAs(MimeType.PDF)]
  });
}

In your script, paymentPDF is FileIterator. I thought that by this, such an error like TypeError: paymentPDF.getAs is not a function occurs. So, how about the following modification?

From:

var paymentPDF = DriveApp.getFilesByName(fileName);

To:

var paymentPDF = DriveApp.getFilesByName(fileName);
if (!paymentPDF.hasNext()) {
  throw new Error("No file.");
}
var paymentPDF = paymentPDF.next();
  • In this modification, it supposes that the file of fileName is only one in Google Drive. When the file of fileName is not existing, an error like No file. occurs. When the file of fileName is existing, the file object is returned. By this, paymentPDF.getAs(MimeType.PDF) can be used.

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM