【问题标题】:Populate email subject line with form entries in Google Scripts使用 Google 脚本中的表单条目填充电子邮件主题行
【发布时间】:2021-08-25 14:57:35
【问题描述】:

我对 Google 脚本完全陌生。我尝试了找到 here 的脚本(由 Snipe 编写并由 Govoni 在第一条评论中编辑)。

我想做的是结合这两个脚本,以获取关于表单提交的电子邮件:

  • 仅显示已回答的问题(有效)
  • 以粗体显示问题(有效)
  • 填充主题行(我无法让它工作)

下面的代码有效。

function newResponse()

{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formName = ss.getSheetByName('Form Responses 1');
var lastRow = formName.getLastRow();
var lastColumn = formName.getLastColumn();
var email = "sample@myemail.com"; 
var name = "My Email";
var subject = 'New form response: ';
var body = '';
var cell = '';
for (var i = 1; i <= lastColumn ; i++)
{
var title = formName.getRange(1,i).getDisplayValue();
var cell = formName.getRange(lastRow, i).getDisplayValue();
if (cell != '' && cell != 0)
{
body = body + '<b>'+ title + '</b>: ' + cell + '<br>';
};
};

MailApp.sendEmail({
to: email,
name: name,
subject: subject,
htmlBody: body
});
}

因此,为了尝试将变量条目添加到主题行,我将“function newResponse()”更改为“function newResponse(e)”并在 MailApp:sendEmail 之前添加了这一行:

// The email subject line should look like this: "New form response: Item (Company, Country)"
// Item, Company and Country are the 2nd, 3rd and 4th columns from my form
subject += e.namedValues[title[1]].toString() + " (" + e.namedValues[title[2]].toString()+ ", "
+ e.namedValues[title[3]].toString()+ ")";

但是当我这样做时,它根本不会发送电子邮件。如果我更改 e.namedValues 并改为输入 [title[0]] 之类的内容,则它会返回最后回答的问题的第一个字母。

我不太确定下一步该尝试什么?

【问题讨论】:

    标签: javascript google-apps-script google-sheets google-forms


    【解决方案1】:

    根据您的代码 sn-p,我想 title 变量包含一个字符串,所以 title[0] 是字符串的第一个字符。如果没有问题是单字符,e.namedValues[title[1]] 将是 undefinedundefined.toString() 会抛出错误,导致整个脚本崩溃。

    您需要保存工作表中所有列的标题数组。

    var titles = [];
    for (var i = 1; i <= lastColumn ; i++) {
      var title = formName.getRange(1,i).getDisplayValue();
      titles.push(title);
      var cell = formName.getRange(lastRow, i).getDisplayValue();
      ...
    }
    

    之后,您就可以使用e.namedValues[titles[1]]。注意我使用titles,数组。

    【讨论】:

    • 非常感谢您:我为这个问题分心,您的代码运行良好!遗憾的是,由于我不存在的声誉,我无法投票给你的答案,但我非常感激。
    • 很高兴我的解决方案有帮助!
    【解决方案2】:

    主题不是高级参数对象的成员,它只是一个 mailapp.senEdmail 参数。

    试试:

    sendEmail(email, subject, '', {name: name, htmlBody: body});
    

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2014-06-17
      • 2019-07-30
      • 2021-07-21
      • 2021-05-10
      相关资源
      最近更新 更多