javascriptgoogle-apps-script

apps script to attach all files to email that exist in a folder


Below is where I am currently at with my code. It works just fine to attach one file. It is only attaching the last file in the folder. I want it to attach all files.

   function email() {   

   // Get attachments folder
  var attachementFolderId = values[cell][11];
  Logger.log("Attachement Folder ID:  " + attachementFolderId)
  var getAttachementFolder = DriveApp.getFolderById(attachementFolderId).getFiles();

   // Get all files from the folder
 var files = DriveApp.getFolderById(attachementFolderId).getFiles();
 while (files.hasNext()) {
   var file = files.next();
   var attachements = file.getAs(MimeType.PDF);
   Logger.log(attachements)
 }

     MailApp.sendEmail({
     to: recipient,
     subject: address,
     htmlBody: "Hello <br><br>" +
               "Address:  " + address + "<br><br>" +
               "Description: " + description,
    attachments: [attachements]
    })
}

Solution

  • Your solution is not right. try like below :

    var attachements = [];
    while (files.hasNext()) {
       var file = files.next();
       attachements.push(file.getAs(MimeType.PDF));// the push method add elements to the attachements array
       Logger.log(attachements)
     }
    

    And in the end :

     MailApp.sendEmail({
     to: recipient,
     subject: address,
     htmlBody: "Hello <br><br>" +
               "Address:  " + address + "<br><br>" +
               "Description: " + description,
    attachments: attachements
    })