【问题标题】:How to Attach Google Drive File with sendMail Function in Apps Script?如何在 Apps 脚本中使用 sendMail 功能附加 Google Drive 文件?
【发布时间】:2018-07-27 15:04:09
【问题描述】:

希望将 Google Drive 中的文件 (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]});
 }

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    根据GAS Documentation on sendMail,看起来attachments 参数需要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() 不是必需的,所以我已经从我的代码中删除了它!

    【讨论】:

    • 我认为应该是listofFiles.next().getBlob()
    • 谢谢杰克,我不确定,因为我以前没有在 PDF 中使用过它!我已经更新了我的答案。
    • 好吧,我收回了。似乎 Google Files 是一个有效的 blob 源
    • 哈哈,对,我也查过了。
    猜你喜欢
    • 2015-07-10
    • 2020-11-26
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多