【问题标题】:Send mail with attached PDF to recipient after confirmation确认后将附有 PDF 的邮件发送给收件人
【发布时间】:2016-05-10 09:57:40
【问题描述】:

我必须每天编辑一个 Google 电子表格文件。当我完成后,我想向人们发送一条消息,通知他们我已经完成了。作为该通知邮件的附件,我想以 PDF 格式向他们发送一张特定的表格(称为报告)。

我发现这个发送电子邮件的选项(并且工作正常):

function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;  // First row of data to process
var numRows = 2;   // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0];  // First column
var message = row[1];       // Second column
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
}
}

有没有办法将特定工作表添加为 PDF?

第二个问题:如何在电子表格中创建某种按钮(“立即发送”),让我轻松发送这封电子邮件,而不必每次都打开脚本编辑器?

【问题讨论】:

    标签: email pdf google-apps-script google-sheets


    【解决方案1】:

    菜单驱动的按需操作

    在 Google 表格用户界面中,菜单项是一种将其设置为按需运行的自然方式。1 Google 的 @ 是学习如何自己执行此操作的好资源987654321@。

    在该教程中,以下代码可将“发送报告”菜单项添加到您的电子表格,选中时将调用 sendReport_() 函数:

    /**
     * A special function that runs when the spreadsheet is open, used to add a
     * custom menu to the spreadsheet.
     */
    function onOpen() {
      var spreadsheet = SpreadsheetApp.getActive();
      var menuItems = [
        {name: 'Send Report', functionName: 'sendReport_'}
      ];
      spreadsheet.addMenu('Custom', menuItems);
    }
    

    sendReport_()函数

    假设我们有一个getPdfBlob() 函数,它将返回一个适合附加到电子邮件的blob。有了这些,sendReport_() 需要做的事情就在这里:

    // From https://stackoverflow.com/a/37149036/1677912
    function sendReport_() {
    
      // Configuration parameters; customize as you wish
      var sheetName = "Report";
      var subject = "Email subject line";
      var recipients = "user1@example.com, user2@example.com";
      var htmlMessage = "Greetings,<br/><br/>"
                      + "Please find today's report attached as a PDF.<br/><br/>"
                      + "Cheers,<br/><br/>Paranoia";
    
      // Get the IDs of the spreadsheet & sheet-of-interest
      var ss = SpreadsheetApp.getActive();
      var sheetId = ss.getSheetByName(sheetName).getSheetId();
    
      // Retrieve the PDF blob
      var pdfBlobArray = getPdfBlobs(ss.getId(),sheetId);
    
      // Send the email + attachment
      MailApp.sendEmail(recipients,subject,"Report attached.", {
        htmlBody: htmlMessage,
        attachments: pdfBlobArray
      });
    }
    

    getPdfBlobs()实用函数

    生成电子表格 PDF 的实用程序出现在 Convert all sheets to PDF with Google Apps Script 中。 这可以调整为返回一个 blob,其中包含您所追求的单张纸的 PDF。

    您必须通过“资源 > 高级驱动器服务...”和开发者控制台启用 Advanced Drive Service。 (有关更多信息,请参阅this。)

    注意:编辑嵌入在此函数中的 URL 参数支持对 PDF 输出的一些奇怪的自定义。

    /**
     * Get one or all sheets in a spreadsheet as PDF file blobs.
     *
     * From: https://stackoverflow.com/a/37149036/1677912
     * Adapted from https://stackoverflow.com/a/30492812/1677912
     *
     * @param {String}  optSSId       (optional) ID of spreadsheet to export.
     *                                If not provided, script assumes it is
     *                                sheet-bound and opens the active spreadsheet.
     * @param {String}  optSheetId    (optional) ID of single sheet to export.
     *                                If not provided, all sheets will export.
     */
    function getPdfBlobs( optSSId, optSheetId ) {
    
      // If a sheet ID was provided, open that sheet, otherwise assume script is
      // sheet-bound, and open the active spreadsheet.
      var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();
    
      // Get URL of spreadsheet, and remove the trailing 'edit'
      var url = ss.getUrl().replace(/edit$/,'');
    
      // Get array of all sheets in spreadsheet
      var sheets = ss.getSheets();
    
      // Loop through all sheets, generating PDF blobs.
      var blobArray = [];
      for (var i=0; i<sheets.length; i++) {
        var sheet = sheets[i];
    
        // If provided a optSheetId, only save it.
        if (optSheetId && optSheetId !== sheet.getSheetId()) continue; 
    
        //additional parameters for exporting the sheet as a pdf
        var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf
            + '&gid=' + sheet.getSheetId()   //the sheet's Id
            // following parameters are optional...
            + '&size=letter'      // paper size
            + '&portrait=true'    // orientation, false for landscape
            + '&fitw=true'        // fit to width, false for actual size
            + '&sheetnames=false&printtitle=false&pagenumbers=false'  //hide optional headers and footers
            + '&gridlines=false'  // hide gridlines
            + '&fzr=false';       // do not repeat row headers (frozen rows) on each page
    
        var options = {
          headers: {
            'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken()
          }
        }
    
        var response = UrlFetchApp.fetch(url + url_ext, options);
    
        var blob = response.getBlob().setName(ss.getName() + ' - ' + sheet.getName() + '.pdf');
    
        // Add blob to our array
        blobArray.push(blob);
      }
    
      // Return array of PDF blobs
      return blobArray;
    }
    
    /**
     * Dummy function for API authorization only.
     * From: https://stackoverflow.com/a/37172203/1677912
     */
    function forAuth_() {
      DriveApp.getFileById("Just for authorization"); // https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579#c36
    }
    

    1这可以进一步扩展为一个插件,这样脚本就不需要附加到特定的电子表格中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2014-02-06
      相关资源
      最近更新 更多