[英]Send an email on submission of a Google form
Whenever users submit a Google Form to my Google Sheet, I want to trigger a OnSubmit function to automatically send an email reply using the email address in the form field, together with a calculated 'right/wrong' data verification of the submission. 每当用户向我的Google表格提交Google表单时,我都想触发一个OnSubmit函数,以使用表单字段中的电子邮件地址自动发送电子邮件回复,并计算提交内容的“正确/错误”数据验证。 Since the latest form submission data goes into the last row of the sheet, I tried the following code to pull out both data from the sheet (even though I could use the function parameter for the Email Address).
由于最新的表单提交数据进入工作表的最后一行,因此我尝试使用以下代码从工作表中提取这两个数据(即使我可以将函数参数用于“电子邮件地址”)。
I also set up the on form submit event trigger and email authorization already. 我还已经设置了表单提交事件触发器和电子邮件授权。 But the emailing doesn't seem to work.
但是,发送电子邮件似乎无效。 Do I still need to run the function in script editor if it is set to trigger on form submission?
如果设置为在表单提交时触发,我是否仍需要在脚本编辑器中运行该函数? The code exceeds execution time when I try clicking on Run though.
当我尝试单击“运行”时,代码超出了执行时间。
function OnSubmit(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = sheet.getLastRow()-1;
var numRows = 1; // Number of rows altogether
// Fetch the range of cells A(last row):G(last row)
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[2]; // Column C of last row
var message = "";
while(row[6] === "") { // Delay until data verification is done
Utilities.sleep(10000);
}
var subject = row[6] // Column G (data verification cell) of last row
MailApp.sendEmail(emailAddress, subject, message);
}
}
I get that you are trying to make the script wait until the calculation is complete. 我知道您正在尝试让脚本等到计算完成。
However, 然而,
while(row[6] === "") {
Utilities.sleep(10000);
}
is a wrong way to go about this: the variable row
isn't changing in the loop. 解决此问题的方法是错误的:变量
row
循环中没有更改。 It could if the data-fetching line var data = dataRange.getValues();
如果数据获取行
var data = dataRange.getValues();
was inside of the while
loop. 在
while
循环内。
But there is a better way to ensure than pending changes actually happen: use 但是有一种比即将发生的更改实际发生更好的方法来确保:
SpreadsheetApp.flush();
before var data = dataRange.getValues();
之前
var data = dataRange.getValues();
This will apply pending computations, and eliminate the need for that while
loop. 这将应用待处理的计算,并消除了
while
循环的需要。 Result: 结果:
function OnSubmit(e) {
SpreadsheetApp.flush();
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange(sheet.getLastRow(), 1, 1, 7);
var data = dataRange.getValues();
var row = data[0];
var emailAddress = row[2]; // Column C of last row
var message = "";
var subject = row[6] // Column G (data verification cell) of last row
MailApp.sendEmail(emailAddress, subject, message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.