1

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)]
  });
}

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

I solve this problem for your comment. Thank you Tanaike :)
@Sehyeon Thank you for replying and testing it. I'm glad your issue was resolved. Thank you, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.