傳送已收錄的內容

程式設計層級:新手
持續時間:20 分鐘
專案類型:透過事件導向觸發條件進行自動化作業

目標

  • 瞭解解決方案的功能。
  • 瞭解 Apps Script 服務在解決方案中的功能。
  • 設定指令碼。
  • 執行指令碼。

認識這項解決方案

如果您想為目標對象提供不同類型的內容,可以讓使用者使用 Google 表單選擇他們要接收的內容。這個解決方案可讓使用者選取感興趣的主題,然後自動以電子郵件傳送他們選擇的內容。

示範:透過 Google 表單和 Gmail 傳送內容

運作方式

這個指令碼會安裝事件導向的觸發條件,會在使用者每次提交表單時執行。每次提交表單時,指令碼都會從 Google 文件範本建立及傳送電子郵件。電子郵件中會包含使用者名稱和他們選取的內容。只要以網址參照,您提供的內容可以是任何類型。

Apps Script 服務

這項解決方案使用下列服務:

  • 指令碼服務:安裝事件導向的觸發條件,會在使用者提交表單時觸發。
  • 文件服務:開啟指令碼用來建立電子郵件的文件範本。
  • 「Mail service」(郵件服務):根據使用者名稱和內容選項,建立並傳送電子郵件。
  • 試算表服務:在指令碼傳送電子郵件後,在「表單回應」工作表中加入確認訊息。

必要條件

如要使用這個範例,您必須具備以下必要條件:

  • Google 帳戶 (Google Workspace 帳戶可能需要取得管理員核准)。
  • 可連上網際網路的網路瀏覽器。

設定指令碼

  1. 點選下方按鈕,建立「傳送收錄內容」試算表的副本。這個解決方案的 Apps Script 專案已附加到試算表。
    建立副本

  2. 在複製的試算表中,依序點選「擴充功能」>「Apps Script」

  3. 在函式下拉式選單中,選取「installTrigger」installTrigger

  4. 按一下「執行」

  5. 出現提示訊息時,請授權執行指令碼。如果 OAuth 同意畫面顯示警告「This app has not verification」(這個應用程式尚未驗證),請依序選取「Advanced」(進階) >「Go to {Project Name} (unsafe)」 (前往 {Project Name} (不安全))

重要事項:如果您多次執行 installTrigger,指令碼會建立多個觸發條件,在使用者提交表單時傳送電子郵件。如要刪除額外的觸發條件並避免電子郵件重複,請按一下「Triggers」(觸發條件) 。在每個額外觸發條件上按一下滑鼠右鍵,然後點選「刪除觸發條件」

執行指令碼

  1. 切換回試算表,然後依序點選「Tools」>「Manage form」 >「Go to live form」
  2. 填寫表單,然後按一下 [提交]
  3. 查看電子郵件,看看是否有包含所選內容連結的電子郵件。

查看程式碼

如要查看這項解決方案的 Apps Script 程式碼,請點選下方的「查看原始碼」

查看原始碼

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) {
  let 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.
  let timestamp = responses.Timestamp[0];
  let email = responses['Email address'][0].trim();
  let name = responses.Name[0].trim();
  let 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).
  let 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.
  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.
  let sheet = SpreadsheetApp.getActiveSheet();
  let row = sheet.getActiveRange().getRow();
  let 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(function(topic) {
  let 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.
  let 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.
  let url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
            docId + "&exportFormat=html";
  let param = {
    method: "get",
    headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  return UrlFetchApp.fetch(url, param).getContentText();
}

貢獻者

本範例是由 Google 在 Google Developers 專家的協助下維護。

後續步驟