Search code examples
javascriptgoogle-apps-scriptgoogle-drive-apigoogle-apps

Attachments on Google Apps Script


I'm having some problem when I put more then one attachments in Google Apps Script to send in a E-mail.

The part of the code that does this is

      reportPDF = doc.getAs('application/pdf')
      reportPDF.setName('Attachment1 - '+ rows[0][0] + ".pdf");
      
      var file1 = destinationFolder.createFile(reportPDF);  
      var file2 = DriveApp.getFilesByName("test.pdf");

      DriveApp.getFileById(doc.getId()).setTrashed(true);
      
      emails.forEach(function(email) {
      MailApp.sendEmail(email, "Attachments  - " + rows[0][0], "Hello!", {
                        name: 'Good Practices',
                        attachments: [file.getAs(MimeType.PDF), file2]

    });

But when I run this, I Have this issue:

Exception: Invalid argument: attachments (line 151, file "Email")

I have a .doc file1 that is filled in and then converted to PDF and another file2 that is already a PDF.

When I run with just the file1, i can send the email, but when i try with file1 and file2, i have this error. Can anyone knows what might be happening?

I run a lot of another suggestions that i read here in stack, but no one of then worked.


Solution

  • Explanation:

    The issue is that file2 is not of a type FILE but an object of the FileIterator class.

    On the other hand, file1 is of a type FILE and this is why it is working properly.

    It is also a good practice to check if the file name exists before you sent the email.

    Solution:

    function myFunction() {
      
      reportPDF = doc.getAs('application/pdf')
      reportPDF.setName('Attachment1 - '+ rows[0][0] + ".pdf");
    
      var file1 = destinationFolder.createFile(reportPDF);  // this is a file
      var folder = DriveApp.getFolderById(folderId); // put here the id of the folder
      var file2 = folder.getFilesByName("test.pdf"); // this is a file iterator
    
      DriveApp.getFileById(doc.getId()).setTrashed(true);
      
      if (file2.hasNext() ) {
          MailApp.sendEmail(emailAddress, "Attachments  - " + rows[0][0], "Hello!",{
          name: 'Good Practices',                  
          attachments: 
              [
               file1.getAs(MimeType.PDF),
               file2.next().getAs(MimeType.PDF)
              ]    
      })};  
    }
    

    References: