Search code examples
javascriptgoogle-sheetsemail-attachments

Fail to Send an email with attachment using Google Apps Script


function SendEmails() {


  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name List").activate();

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  var lr = ss.getLastRow(); 

  var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email Template").getRange(1, 1).getValue();

  var quotaLeft = MailApp.getRemainingDailyQuota();
  //Logger.log(quotaLeft);
  if ((lr-1) > quotaLeft){
     Browser.msgBox("You have " + quotaLeft + " left and you're trying  to send " + (lr-1) + "emails. Emails were not sent.");
     } else {

  for (var i = 2;i<=lr;i++){

       var currentName = ss.getRange(i, 1).getValue();
       var currentAppNo = ss.getRange(i, 2).getValue();
       var currentEmail = ss.getRange(i, 3).getValue();

       var messageBody = templateText.replace("{First Name}",currentName).replace("{App No}",currentAppNo);
       var subjectLine = "CONGRATULATION ON YOUR VAL APPROVAL " + currentName
       var attachmentBody = DriveApp.getFilesByName("THE ROOM SCRIPT.pdf");


      MailApp.sendEmail(currentEmail, subjectLine, messageBody)

    } //close for loop

          } //close else statement
}

I have a Google Spreadsheet with a list of emails. I want to build a routine that sends email automatically to those email addresses. I also want to attach a PDF to this email. The PDF file is located on my Google Drive.

This does not seem to work


Solution

  • Here are two things that you may want to change in your script.

    1. getFilesByName() gets a collection of files (as a FileIterator object) with that name. If there is just one such file, you'll need to change that line to
        var attachmentBody = DriveApp.getFilesByName("THE ROOM SCRIPT.pdf").next; // To get the first such file
    

    Ref doc here.

    1. As @ross said, the sendMail() function needs to include the attachment like so:
        MailApp.sendEmail(currentEmail, subjectLine, messageBody, {
            attachments: [attachmentBody.getAs(MimeType.PDF)]
        });
    

    Ref doc here.