这是demo spreadsheet and script 的链接。只需复制电子表格并测试代码即可。
通过突出显示电子表格中的 1 行或多行数据并从脚本编辑器运行 emailFeedback 函数来测试脚本。或者,您选择了 1 行或更多行,您可以从电子表格中的“自定义工具”菜单执行脚本。
我把它分成两个函数。第一个函数emailFeedback 获取您在电子表格中选择的行,并循环遍历每一行数据,并为每一行调用第二个函数sendEmail,前提是有反馈和文本(可以添加更多验证和错误处理)。
function emailFeedback() {
var ss = SpreadsheetApp.getActiveSheet();
var range = ss.getActiveRange();
var numRows = range.getNumRows();
var values = range.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
var to = row[1];
var story = row[2];
var feedback = row[3];
if (feedback.length > 0 && story.length > 0) {
// make sure valid story and feedback before sending
sendEmail(to, story, feedback);
}
}
};
GmailApp 用于发送上面 cmets 中 igor 建议的 html 格式的电子邮件。 plainTxtBody 可能会被省略,但如果收件人无法解析 html 格式的电子邮件,它可能会很有用。 storyHTML 和 feedbackHTML 将用户表单提交中的换行符替换为 <p> 标签,以便您在电子邮件中获得适当的间距。
function sendEmail(to, story, feedback) {
var sendToName = to.split('@')[0];
// email content
var emailSubject = "Feedback on your story submission";
// plain text body - just in case receiver can't parse html formatted email
var plainTxtBody = "Hi " + sendToName + ",\n" +
"You wrote:\n" + story + "\n" +
"Our feedback:\n" + feedback;
// html formatting isn't necessary, but nice for reading :)
var htmlBody = '<html><body>';
var htmlFooter = '</body></html>';
// replacing newline characters with paragraph breaks to make it more readable
var storyHTML = story.replace(/\n/g, "</p><p>");
var feedbackHTML = feedback.replace(/\n/g, "</p><p>");
var emailMessage = "<p>Hi " + sendToName + ",</p>" +
"<p><strong>You wrote:</strong><p>" +
"<p>" + storyHTML + "</p>" +
"<hr>" +
"<p><strong>Here is our feedback:</strong></p>" +
"<p>" + feedbackHTML + "</p>";
htmlBody += emailMessage + htmlFooter;
// GmailApp must have default recipient, subject, body attributes followed by jsobject options {}
// Differs from MailApp syntax but has more options -- see documentation on GmailApp
GmailApp.sendEmail(to, emailSubject, plainTxtBody, {
htmlBody: htmlBody,
});
};
希望这有帮助:)