Tệp đính kèm trên Google Apps Script

Jan 06 2021

Tôi đang gặp một số vấn đề khi đặt nhiều hơn một tệp đính kèm trong Google Apps Script để gửi trong E-mail.

Một phần của mã thực hiện điều này là

      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]

    });

Nhưng khi tôi chạy cái này, tôi gặp sự cố này:

Ngoại lệ: Đối số không hợp lệ: tệp đính kèm (dòng 151, tệp "Email")

Tôi có một tệp .doc 1 được điền và sau đó được chuyển đổi thành PDF và một tệp 2 khác đã là PDF.

Khi tôi chỉ chạy với tệp1, tôi có thể gửi email, nhưng khi tôi thử với tệp1 và tệp2, tôi gặp lỗi này. Bất cứ ai có thể biết những gì có thể đang xảy ra?

Tôi chạy rất nhiều đề xuất khác mà tôi đã đọc ở đây trong ngăn xếp, nhưng không ai trong số đó hoạt động.

Trả lời

1 Marios Jan 06 2021 at 23:09

Giải trình:

Vấn đề là đó file2 không phải là một loại FILE mà là một đối tượng của lớp FileIterator .

Mặt khác, file1 một loại FILE và đây là lý do tại sao nó hoạt động bình thường.

Bạn cũng nên kiểm tra xem tên tệp có tồn tại hay không trước khi bạn gửi email.

Giải pháp:

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)
          ]    
  })};  
}

Người giới thiệu:

  • getFilesByName (tên)
  • createFile