Search code examples
emailgoogle-apps-scriptgmail

Send multiple attachments using DriveApp.getFileById in Google Apps Script


I am trying to get a script running that takes multiple file IDs from a Google Sheet and attaches them to an email. I cannot get multiple files to be attached using DriveApp.getFileById.

The script runs and fires off an email, but with no attachments.

function createAndSendDocument(values) {

  // Get the email address of the active user
  var email = Session.getActiveUser().getEmail();

  // Get the name of the document to use as an email subject line.
  var subject = 'New Paperwork';

    //Let's add the attachments variables
  var attachmentstring = values["Which documents do you want to attach?"];
  var array = attachmentstring.toString().split(",");
  var blobs = [];
  var x = 0;
  for (var i = 0; i < array.length; i++) {
   
    //check if even
    if (i % 2 === 0) {
        blobs[x] = array[i];
        x++;
    }
    
  }
  
  // Append a new string to the "url" variable to use as an email body.
  var body = 'your doc: ' + blobs[0] + blobs[1] + array[0] + array[1] + "length:" + array.length;

  // Send yourself an email with a link to the document.
  GmailApp.sendEmail(email, subject, body, {attachments: blobs});
}

I edited the original post to include the snippet of code. Here is the output of the blobs and array.

undefinedundefinedW-4 2019.pdf1YjQqFNze8VX0L6wZ9O3Y9AJNznR8jfxqlength:4


Solution

  • This code worked:

    function createAndSendDocument(values) {
    
    // Get the email address of the active user
      var email = Session.getActiveUser().getEmail();
    
      // email subject line.
      var subject = 'New Paperwork';
    
        // add the attachments variables
      var attachmentstring = values["Which documents do you want to attach?"];
      var array = attachmentstring.toString().split(",");
      var blobs = [];
      var x = 0;
      for (var i = 0; i < array.length; i++) {
       
        //check if even
        if (i % 2 === 0) {
    
        }
        else 
        {
            blobs[x] = DriveApp.getFileById(array[i]).getBlob();
            x++;
        }
        
      }
      
      // an email body.
      var body = 'Hello';
    
      // Send an email with attachments
      GmailApp.sendEmail(email, subject, body, {attachments: blobs});
    }