提交 Google 表单时发送确认电子邮件

时间:2021-04-15 14:33:22

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

我正在尝试向已提交表单的用户发送电子邮件。它有时有效,有时无效。我想这是因为触发器由于某种原因并不总是起作用,但我不明白为什么。

以下是用于提交表单的 Google 表格中的 Google Apps 脚本:

var EMAIL_TEMPLATE_DOC_URL = 'https://docs.google.com/document/d/1-HToXjwUMOB75QiU47Dt0Kf-cHo0a6YylA4dk3el43s/edit?usp=sharing&resourcekey=0-6SIiX993oZWMFr6W3HMyXQ';
var EMAIL_SUBJECT = 'Registration Link';
var FROM = 'Me';
var REPLY = 'info@test.com';

/**
 * 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 timestampdate = responses.Timestamp[0];
  var email = responses['Email Address'][0].trim();
  var name = responses['First name'][0].trim();
  var timestamp = timestampdate.substring(0,1) + timestampdate.substring(2,4) + timestampdate.substring(5,9) + timestampdate.substring(10,11) + timestampdate.substring(12,14) + timestampdate.substring(15,16);
  var uniquelink = 'https://docs.google.com/forms/d/e/1FAIpQLSevzEo3LwFRW60OdJw2UridvI8XVp84afC8na4YjlRDZQKflQ/viewform?usp=pp_url&entry.504080580=' + timestamp;

  // If there is at least one topic selected, send an email to the recipient.
  var status = '';
  if (uniquelink.length > 0) {
    MailApp.sendEmail({
      to: email,
      name: FROM,
      replyTo: REPLY,
      subject: EMAIL_SUBJECT,
      htmlBody: createEmailBody(name, uniquelink),
    });
    status = 'Sent';
  }
  else {
    status = 'No link, not sent';
  }

  // 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} unique link - Unique link for each user, based on timestamp.
 * @return {string} - The email body as an HTML string.
 */
function createEmailBody(name, uniquelink) {
 
  // 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(/{{LINK}}/g, uniquelink);
  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();
}

我如何才能知道是什么原因导致电子邮件无法发送?

谢谢!

0 个答案:

没有答案