Can't attach multiple Blob objects as attachme

2019-08-01 14:30发布

问题:

I'm creating an google-app-script that converts documents and sends an email.

I have created two functions, one for converting a Google Doc to Microsoft Word and one for converting Google Sheets to Microsoft Excel. Both of these functions return a Blob object successfully.

I have been able to use the documented MailApp.sendEmail function to send an individual blob. But I keep running into an invalid argument error when I try to send two blobs in the same email.

My script is:

    //Convert Google Sheet page to Microsoft Excel Document, return BLOB
    function convert2Excel(docID) {

  var file          = DriveApp.getFileById(docID);
  var url           = 
  "https://docs.google.com/spreadsheets/d/"+docID+"/export?forma‌t=xlsx";
  var token         = ScriptApp.getOAuthToken();
  var response      = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  var fileName = file.getName() + '.xlsx';
  return [response.getBlob().setName(fileName)];

};

//Convert Google Doc page to Microsoft Word Document, return BLOB for emailing
function convert2Word(docID){

  var file       = DriveApp.getFileById(docID);
  var url        = "https://docs.google.com/document/d/"+docID+"/export?forma‌t=docx";
  var token      = ScriptApp.getOAuthToken();
  var response   = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });
  var fileName = file.getName() + '.docx';
  return [response.getBlob().setName(fileName)];

 };

//Send email with attachments
function sendEmail(att1,att2){
MailApp.sendEmail('email@email.com', 'The Subject', 'A Message', {attachments: [att1, att2]});
};

var att1=convert2Excel('sheetID string');
var att2=convert2Word('docID string');
sendEmail(att1,att2);

According to the documentation, this should work but I can't get multiple blob objects to work.

回答1:

The reason your code is not working with 2 attachments is that you are passing an array of arrays to the attachments argument of .sendMail()

There are 2 ways to get your code working. The line: return [response.getBlob().setName(fileName)]; By returning the blob inside the square bracket you are actually returning an array containing a blob. You can see this in the debugger:

Remove the square brackets from the line return [response.getBlob().setName(fileName)]; to return the actual blob instead. In the debugger:

Alternatively you could leave the square brackets and add [0] to att1 and att2 on the line MailApp.sendEmail('email@email.com', 'The Subject', 'A Message', {attachments: [att1, att2]}); }; Like this : MailApp.sendEmail('email@email.com', 'The Subject', 'A Message', {attachments: [att1[0], att2[0]]}); };