发送精选内容

编码水平:初级
时长:20 分钟
项目类型:使用 事件驱动型触发器实现自动化

目标

  • 了解此解决方案的功能。
  • 了解 Apps 脚本服务在此解决方案中的功能。
  • 设置脚本。
  • 运行脚本。

关于此解决方案

如果您有多种类型的内容想要提供给受众群体,可以使用 Google 表单让用户选择要从您那里接收哪些内容。 此解决方案可让用户选择感兴趣的主题,然后自动通过电子邮件向他们发送所选内容。

演示如何通过 Google 表单和 Gmail 发送内容

运作方式

该脚本会安装一个事件驱动型触发器,该触发器会在用户每次提交表单时运行。每次提交表单时,该脚本都会根据 Google 文档模板创建并发送电子邮件。电子邮件中包含用户的姓名及其选择的内容。您提供的内容可以是任何类型,只要它由网址引用即可。

Apps 脚本服务

此解决方案使用以下服务:

  • 脚本服务:安装事件驱动型触发器,该触发器会在有人提交表单时运行。
  • 文档服务:打开脚本用于创建电子邮件的 文档模板。
  • 邮件服务:创建并发送包含 用户姓名和所选内容的电子邮件。
  • 电子表格服务:在脚本发送电子邮件后,向表单回复 工作表添加 确认信息。

前提条件

如需使用此示例,您需要满足以下前提条件:

  • Google 账号(Google Workspace 账号可能需要管理员批准)。
  • 可访问互联网的网络浏览器。

设置脚本

  1. 点击以下按钮,复制发送精选内容 Google 表格。此解决方案的 Apps 脚本项目已附加到该电子表格:

    复制聊天机器人

  2. 在复制的表格中,依次点击扩展程序 > Apps 脚本

  3. 在函数下拉列表中,选择 installTrigger

  4. 点击运行

  5. 根据提示为脚本授权。 <<../_snippets/oauth.md>>

重要提示:如果您多次运行installTrigger,脚本会创建 多个触发器,每个触发器都会在用户提交表单时发送电子邮件。如需 删除多余的触发器并避免重复发送电子邮件,请点击 触发器 。右键点击每个多余的触发器,然后点击删除触发器

运行脚本

  1. 切换回电子表格,然后依次点击工具 > 管理表单 > 前往实际表单
  2. 填写表单,然后点击提交
  3. 查看您的电子邮件,找到一封包含指向您所选内容的链接的电子邮件。

查看代码

如需查看此解决方案的 Apps 脚本代码,请点击 查看源代码

查看源代码

Code.gs

solutions/automations/content-signup/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/content-signup

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// To use your own template doc, update the below variable with the URL of your own Google Doc template.
// Make sure you update the sharing settings so that 'anyone'  or 'anyone in your organization' can view.
const EMAIL_TEMPLATE_DOC_URL =
  "https://docs.google.com/document/d/1enes74gWsMG3dkK3SFO08apXkr0rcYBd3JHKOb2Nksk/edit?usp=sharing";
// Update this variable to customize the email subject.
const EMAIL_SUBJECT = "Hello, here is the content you requested";

// Update this variable to the content titles and URLs you want to offer. Make sure you update the form so that the content titles listed here match the content titles you list in the form.
const topicUrls = {
  "Google Calendar how-to videos":
    "https://www.youtube.com/playlist?list=PLU8ezI8GYqs7IPb_UdmUNKyUCqjzGO9PJ",
  "Google Drive how-to videos":
    "https://www.youtube.com/playlist?list=PLU8ezI8GYqs7Y5d1cgZm2Obq7leVtLkT4",
  "Google Docs how-to videos":
    "https://www.youtube.com/playlist?list=PLU8ezI8GYqs4JKwZ-fpBP-zSoWPL8Sit7",
  "Google Sheets how-to videos":
    "https://www.youtube.com/playlist?list=PLU8ezI8GYqs61ciKpXf_KkV7ZRbRHVG38",
};

/**
 * Installs a trigger on the spreadsheet for when someone submits a form.
 */
function installTrigger() {
  ScriptApp.newTrigger("onFormSubmit")
    .forSpreadsheet(SpreadsheetApp.getActive())
    .onFormSubmit()
    .create();
}

/**
 * Sends a customized email for every form response.
 *
 * @param {Object} event - Form submit event
 */
function onFormSubmit(e) {
  const 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.
  const timestamp = responses.Timestamp[0];
  const email = responses["Email address"][0].trim();
  const name = responses.Name[0].trim();
  const 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).
  const topics = Object.keys(topicUrls).filter((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.
  let 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.
  const sheet = SpreadsheetApp.getActiveSheet();
  const row = sheet.getActiveRange().getRow();
  const column = e.values.length + 1;
  sheet.getRange(row, column).setValue(status);

  console.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) {
  let topicsHtml = topics
    .map((topic) => {
      const 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.
  const docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
  let 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.
  const url = `https://docs.google.com/feeds/download/documents/export/Export?id=${docId}&exportFormat=html`;
  const param = {
    method: "get",
    headers: { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
    muteHttpExceptions: true,
  };
  return UrlFetchApp.fetch(url, param).getContentText();
}
</section>

贡献者

此示例由 Google 在 Google 开发者专家的帮助下维护。

后续步骤