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)]
});
}
CodePudding user response:
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 offileName
is not existing, an error likeNo file.
occurs. When the file offileName
is existing, the file object is returned. By this,paymentPDF.getAs(MimeType.PDF)
can be used.