0

I'm trying to do the same thing as this question:

Send an email with attachment using Google Apps Script

But with the attachment names as cells in the spreadsheet. My code is here:

function sendEmailsandAttachments() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 1; // First row of data to process
  var numRows = 3; // Number of rows to process
  // Fetch the range of cells A2:B3
  // Need to extend this. That 1 3 is starting, ending columns!
  var dataRange = sheet.getRange(startRow, 1, numRows, 3);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i in data) {
    var row = data[i];
    var emailAddress = row[0]; // First column
    var message = row[1]; // Second column
    var examname = row[2];
    var full_examname = "Teaching/PHY2211/Exams/" + examname;
    Logger.log(full_examname);
    //var file = row[2]; //third column
    var file = DriveApp.getFilesByName(full_examname).next();
    var subject = 'Sending emails from a Spreadsheet';
    MailApp.sendEmail(emailAddress, subject, message, {attachments: file} );
  }
}

I can see in the log that my filenames are actually working, but I just get "cannot retreive the next object: iterator". My guess is I don't understand exactly why .next() is there (because I don't), but it seems like attachments is expecting some kind of array, but I just want to pass a single file to it.

1 Answer 1

1

Replace

var file = DriveApp.getFilesByName(full_examname).next();
var subject = 'Sending emails from a Spreadsheet';
MailApp.sendEmail(emailAddress, subject, message, {attachments: file} );

by

var subject = 'Sending emails from a Spreadsheet';
var files =  DriveApp.getFilesByName(full_examname);
if(files.hasNext()){
   var file = files.next();
   MailApp.sendEmail(emailAddress, subject, message, {attachments: file} );
} else {
  // Put here what you want that the code do when no file is found.
}

Brief explanation

getFilesbyName returns a file iterator. next() it's there to get the file referred by the file iterator but it will only work if a file was found. hasNext() should be there to check if a file was found.

Your Answer

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

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