Gmail应用程序脚本:基于Google Drive URL的附件

时间:2014-10-14 00:22:44

标签: google-apps-script gmail google-sheets

我使用的是我在这里找到的邮件合并脚本,但是我找不到合适的类来附加文件(第14行和第15行)。

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 1;   // Number of rows to process
  // Fetch the range of cells A2:B2
  var dataRange = sheet.getRange(startRow, 1, numRows, 1)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[3];  // First column
    var message = row[10];       // Second column
    var subject = row[6];
    var attachment = Attachment.setUrl(row[11]);
    MailApp.sendEmail(emailAddress, subject, message, {attachments: attachment});
  }
}

我已经尝试了一些附件功能的变体,但我每次都会遇到错误。行对应于Google表格中的列,行[11]是Google云端硬盘中图片的网址。

2 个答案:

答案 0 :(得分:0)

这是您的脚本的一个工作示例:您有2个错误:

  1. 范围定义只有一列
  2. 附件的参数应该是一个blob数组

  3. function sendEmails() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var startRow = 2;  // First row of data to process
      var numRows = 1;   // Number of rows to process
      // Fetch the range of cells A2:B12 since you use row[11], the data must at least be 12 cells wide
      var dataRange = sheet.getRange(startRow, 1, numRows, 12);
      // Fetch values for each row in the Range.
      var data = dataRange.getValues();
      for (i in data) {
        var row = data[i];
        var emailAddress = row[3];  // Fourth column
        var message = row[10];       // elevenths column
        var subject = row[6];
        var attachment = [UrlFetchApp.fetch(row[11]).getBlob()];
        MailApp.sendEmail(emailAddress, subject, message, {attachments: attachment});
      }
    }
    

    另请注意,url必须有效且文件必须公开共享:example:

    https://drive.google.com/uc?export=view&id=0B3qSFd3iikE3TUFFLTc5MDE0MzkwLWQxYWItNDkwNy05ZjVkLWIyZDhiZDM4MjdmMg
    

答案 1 :(得分:0)

类似于Serge insas的回答,这是我在使用UrlFetchApp.fetch时要绕过401错误所要做的事情

var fileUrl = row[11] // Based on OP's case

var attachment = [
   UrlFetchApp.fetch(fileUrl, {
      headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
   }).getBlob(),
]

MailApp.sendEmail(emailAddress, subject, message, {attachments: attachment});