Google-apps-script 不会在 onEdit 函数中发送电子邮件

Google-apps-script will not send email inside an onEdit function

我有一个脚本可以在编辑电子表格时发送电子邮件。脚本运行,但 MailApp 语句不起作用。

这是执行日志:

[15-01-27 14:15:17:951 EST] SpreadsheetApp.getActiveSpreadsheet() [0 seconds] [15-01-27 14:15:17:951 EST] Spreadsheet.getActiveRange() [0 seconds] [15-01-27 14:15:17:952 EST] Range.getRow() [0 seconds] [15-01-27 14:15:17:952 EST] Range.getLastRow() [0 seconds] [15-01-27 14:15:17:952 EST] Range.getColumn() [0 seconds] [15-01-27 14:15:17:952 EST] Range.getLastColumn() [0 seconds] [15-01-27 14:15:17:955 EST] Starting execution [15-01-27 14:15:17:969 EST] Logger.log([{"range":{"rowStart":79,"rowEnd":79,"columnEnd":6,"columnStart":6},"source":{},"value":"Xxxx","user":{}}, []]) [0 seconds] [15-01-27 14:15:17:969 EST] SpreadsheetApp.getActiveSpreadsheet() [0 seconds] [15-01-27 14:15:18:058 EST] Spreadsheet.getSheets() [0.088 seconds] [15-01-27 14:15:18:145 EST] Spreadsheet.getSheets() [0.086 seconds] [15-01-27 14:15:18:145 EST] Logger.log([Customer row = 79, []]) [0 seconds] [15-01-27 14:15:18:145 EST] Sheet.getRange([79, 6]) [0 seconds] [15-01-27 14:15:18:233 EST] Sheet.getDataRange() [0.087 seconds] [15-01-27 14:15:18:324 EST] Range.getValues() [0.091 seconds] [15-01-27 14:15:18:327 EST] Execution failed: You do not have permission to call sendEmail (line 21, file "Code") [0.368 seconds total runtime]

我在其他脚本上使用了 mailApp.sendEmail,效果很好。这是附加到 spreadsheet/form 的第二个脚本,第一个还从 formSubmit 发送电子邮件。我已允许所有触发器和权限。

感谢任何帮助 代码如下:

function onEdit(e) {
  Logger.log(JSON.stringify(e));
  var ss = SpreadsheetApp.getActiveSpreadsheet();                
  var sheet1 = ss.getSheets()[0]
  var sheet2 = ss.getSheets()[4];       

  var column = Number(e.range.columnStart);

  if(column != 6){return};
  var Customer = Number(e.range.rowStart);
  Logger.log('Customer row = '+Customer);

  var name = sheet1.getRange(Customer,6);
  var emailArray = sheet2.getDataRange().getValues();
  for (i=0;i < emailArray.length;i++){

    if (name == emailArray[i][0]) { 
     var email_address = emailArray[i][1];
    }
  }                 

  var subject = "Job assignment";
  var body    = "X";

  MailApp.sendEmail(email_address,subject,body);
}

您收到此错误是因为您在 onEdit() 触发器内调用 sendMail。您不能在 onEdit 中调用 URLFetch 或 MailApp 方法。

就像其他答案所说的那样,您不能从普通的 onEdit 调用 sendMail。

要修复:将 onEdit 重命名为其他名称,例如 "onEditTrigger" 和 manually install the trigger from the "Resources" menu.

That link also explains the difference, including the restriction you just found out, between the different types of triggers. In this case, onEdit is a simple trigger while my onEditTrigger is an installable trigger