如何在Apps脚本中附加带有sendMail功能的Google云端硬盘文件?

时间:2018-02-16 16:42:48

标签: google-apps-script

希望将Google云端硬盘中的文件(pdfName)附加到Apps脚本中的sendMail功能。目前没有使用下面的代码。其他一切都很完美。只是连接部分有问题。

function send(formObj) {
  var to = formObj.email;
  var body = formObj.body;
  var sheetName = "POTemplate";
  var sourceSpreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
  var poNo = sourceSheet.getRange("b2").getValue();
  var pdfName = "Sample PO Hi Eric " + poNo;
  var subject = poNo + " Good morning, Eric";
  var attach = DriveApp.getFilesByName(pdfName);
   MailApp.sendEmail(to, subject, body, {attachments:[attach]});
 }

1 个答案:

答案 0 :(得分:1)

看来,根据GAS Documentation on sendMailattachments参数需要BlobSource[]documentation)。但是getFilesByName()返回FileIterator。您需要为MailApp提供实现BlobSource的任何文件类型。

所以澄清主要问题是你试图给sendMail一个文件列表(以FileIterator的形式),而不只是一个文件。

所以这样的事情应该有效:

function send(formObj) {
  var to = formObj.email;
  var body = formObj.body;
  var sheetName = "POTemplate";
  var sourceSpreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
  var poNo = sourceSheet.getRange("b2").getValue();
  var pdfName = "Sample PO Hi Eric " + poNo;
  var subject = poNo + " Good morning, Eric";


  var listOfFiles = DriveApp.getFilesByName(pdfName); //returns FileIterator of files that match name given.
  if(listOfFiles.hasNext()){ //We should check if there is a file in there and die if not.
    var file = listOfFiles.next(); //gets first file in list.
    MailApp.sendEmail(to, subject, body, {attachments:[file]});
  }else{
    console.log("Error no file in listOfFiles. Email not sent.");
  }
 }

编辑:我刚做了一些测试,看起来对于PDF来说,getBlob()不是必需的,所以我已将其从我的代码中删除了!