提交表单后发送电子邮件的 Google 表单应用脚本

Posted

技术标签:

【中文标题】提交表单后发送电子邮件的 Google 表单应用脚本【英文标题】:Google form Apps Script to send email after form submission 【发布时间】:2021-11-11 18:32:53 【问题描述】:

我正在尝试修改 here 和 here 解释的 google-form 应用脚本。 该脚本运行良好,没有任何问题。 但我的问题是,在从主题列表中选择其中一个选项之前,此脚本不会发送电子邮件。而且在我的表格中没有主题和任何选项。

我的要求

我想要一个脚本,即使没有选择主题列表中的选项,也会自动响应。

例如。该脚本应该可以在没有 Topics 选项的 google-form 的情况下工作。

请帮我修改这个脚本。 非常感谢您的帮助。

Original Script

var EMAIL_TEMPLATE_DOC_URL = 'https://docs.google.com/document/d/1HGXj6551jxUqFqxsuYMWovI0_nypSUPIdlc-RXf2pHE/edit?usp=sharing';
var EMAIL_SUBJECT = 'Howdy, here is the content you requested';

var topicUrls = 
  'Nutrition': 'https://youtu.be/kCjDirATBos',
  'Reprogramming Habits': 'https://www.mindful.org/category/meditation/',
  'Urban Food': 'https://www.urbanfarm.org/',
  'Water Design': 'https://greywateraction.org/',
;

/**
 * Installs a trigger on the Spreadsheet for when a Form response is submitted.
 */
function installTrigger() 
  ScriptApp.newTrigger('onFormSubmit')
      .forSpreadsheet(SpreadsheetApp.getActive())
      .onFormSubmit()
      .create();


/**
 * Sends a customized email for every response on a form.
 * 
 * @param Object event - Form submit event
 */
function onFormSubmit(e) 
  var responses = e.namedValues;

  // If the question title is a label, it can be accessed as an object field.
  // If it has spaces or other characters, it can be accessed as a dictionary.
  var timestamp = responses.Timestamp[0];
  var email = responses['Email Address'][0].trim();
  var name = responses.Name[0].trim();
  var topicsString = responses.Topics[0].toLowerCase();

  // Parse topics of interest into a list (since there are multiple items
  // that are saved in the row as blob of text).
  var topics = Object.keys(topicUrls).filter(function(topic) 
    // indexOf searches for the topic in topicsString and returns a non-negative
    // index if the topic is found, or it will return -1 if it's not found.
    return topicsString.indexOf(topic.toLowerCase()) != -1;
  );

  // If there is at least one topic selected, send an email to the recipient.
  var status = '';
  if (topics.length > 0) 
    MailApp.sendEmail(
      to: email,
      subject: EMAIL_SUBJECT,
      htmlBody: createEmailBody(name, topics),
    );
    status = 'Sent';
  
  else 
    status = 'No topics selected';
  

  // Append the status on the spreadsheet to the responses' row.
  var sheet = SpreadsheetApp.getActiveSheet();
  var row = sheet.getActiveRange().getRow();
  var column = e.values.length + 1;
  sheet.getRange(row, column).setValue(status);

  Logger.log("status=" + status + "; responses=" + JSON.stringify(responses));


/**
 * Creates email body and includes the links based on topic.
 *
 * @param string recipient - The recipient's email address.
 * @param string[] topics - List of topics to include in the email body.
 * @return string - The email body as an HTML string.
 */
function createEmailBody(name, topics) 
  var topicsHtml = topics.map(function(topic) 
  var url = topicUrls[topic];
    return '<li><a href="' + url + '">' + topic + '</a></li>';
  ).join('');
  topicsHtml = '<ul>' + topicsHtml + '</ul>';
  
  // Make sure to update the emailTemplateDocId at the top.
  var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
  var emailBody = docToHtml(docId);
  emailBody = emailBody.replace(/NAME/g, name);
  emailBody = emailBody.replace(/TOPICS/g, topicsHtml);
  return emailBody;


/**
 * Downloads a Google Doc as an HTML string.
 * 
 * @param string docId - The ID of a Google Doc to fetch content from.
 * @return string The Google Doc rendered as an HTML string.
 */
function docToHtml(docId) 

  // Downloads a Google Doc as an HTML string.
  var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
            docId + "&exportFormat=html";
  var param = 
    method: "get",
    headers: "Authorization": "Bearer " + ScriptApp.getOAuthToken(),
    muteHttpExceptions: true,
  ;
  return UrlFetchApp.fetch(url, param).getContentText();



原始的 Google 表单

【问题讨论】:

【参考方案1】:

尝试替换

  if (topics.length > 0) 

...与:

  if (!topics.length) 
    topics = ['(no topics selected)'];
  
  if ((true)) 

【讨论】:

以上是关于提交表单后发送电子邮件的 Google 表单应用脚本的主要内容,如果未能解决你的问题,请参考以下文章

按下按钮后如何使“提交”表单从 Ajax 工作

如何在 Swift 中确认订单后发送电子邮件

使用特定变量在Google表单提交上发送电子邮件

安排从现在起 24 小时后发送电子邮件?

停止提交表单,直到在 ajax 中打开模式

使用表单提交重定向进行延迟