Google-apps-script – Send email with an attachment located in Google Drive

attachmentgoogle-apps-scriptgoogle-drive

I want to send a PDF attachment located on Google Drive from a Sheet.

Code I'm using is:

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 8;   // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 2)
  // Fetch values for each row in the Range.
  var file = DriveApp.getFilesByName('ScriptCarPass.pdf')
  var data = dataRange.getValues();
  for (i in data) {

    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "Sending emails from a Spreadsheet";
    MailApp.sendEmail(emailAddress, subject, message, {attachments: file});
  }
}

Everything works fine except the attachment – i.e. if I run without the attachment it works fine.

I keep getting error Invalid argument: inlineImages

I've also tried with:

 attachments: [file.getAs(MimeType.PDF)]

but that gives error that .getAs isn't recognised.

Best Answer

DriveApp.getFilesByName() returns a file iterator. You therefore need to slightly modify the sendMail() arguments.

MailApp.sendEmail(emailAddress, subject, message, 
   {attachments: file.next().getBlob()}
);