1

This question already has an answer here:

I am very new to Google Apps Script and struggling. Here is my problem: Trying to send multiple emails via spreadsheet. Want to attach a PDF to those mails. Getting the following error:

TypeError: Cannot call method "getAs" of undefined.

This is the code (primarily taken from Send an email with attachment using Google Apps Script):

function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(1, 2);  
var subject = range.getValues();   
var range = sheet.getRange(1, 9);  
var numRows = range.getValues();   
var startRow = 4;                  
var dataRange = sheet.getRange(startRow, 1, numRows,9 ) 
var data = dataRange.getValues();  
for (i in data) {
 var row = data[i];
  var emailAddress = row[0];      
  var message = row[8];           
 var file = DriveApp.getFilesByName('PPT A4.pdf');
 MailApp.sendEmail(emailAddress, subject, message, {
 name: 'Automatic Emailer Script',
 attachments: [file[0].getAs(MimeType.PDF)]
});
    }
}

What am I doing wrong?

marked as duplicate by user79865, Community Sep 19 '15 at 21:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    You are copying code from a wrong answer, that's what... Generally, you'll get more competent help with Google Apps Script on Stack Overflow. – user79865 Sep 19 '15 at 21:03
1

The method DriveApp.getFilesByName returns a file iterator, not an array. This is why file[0] is undefined. Use file.next() (after checking that file.hasNext() is true; if it's false then there is no file with that name).

Not the answer you're looking for? Browse other questions tagged or ask your own question.