Gửi nội dung chọn lọc

Cấp độ lập trình: Sơ cấp
Thời lượng: 20 phút
Loại dự án: Tự động hoá bằng điều kiện kích hoạt dựa trên sự kiện

Mục tiêu

  • Hiểu rõ chức năng của giải pháp.
  • Hiểu rõ chức năng của các dịch vụ Apps Script trong giải pháp.
  • Thiết lập tập lệnh.
  • Chạy tập lệnh.

Giới thiệu về giải pháp này

Nếu có nhiều loại nội dung mà bạn muốn cung cấp cho khán giả, bạn có thể cho phép người dùng chọn nội dung mà họ nhận được từ bạn bằng Google Biểu mẫu. Giải pháp này cho phép người dùng chọn các chủ đề mà họ quan tâm, sau đó tự động gửi email cho họ về nội dung đã chọn.

Bản minh hoạ cách gửi nội dung bằng Google Biểu mẫu và Gmail

Cách hoạt động

Tập lệnh cài đặt một điều kiện kích hoạt dựa trên sự kiện chạy mỗi khi người dùng gửi biểu mẫu. Với mỗi lần gửi biểu mẫu, tập lệnh sẽ tạo và gửi email từ một mẫu Google Tài liệu. Email này bao gồm tên của người dùng và nội dung mà họ đã chọn. Nội dung mà bạn cung cấp có thể thuộc bất kỳ loại nào miễn là được tham chiếu bằng một URL.

Dịch vụ Apps Script

Giải pháp này sử dụng các dịch vụ sau:

  • Dịch vụ tập lệnh: Cài đặt điều kiện kích hoạt dựa trên sự kiện chạy bất cứ khi nào có người gửi biểu mẫu.
  • Dịch vụ tài liệu: Mở mẫu Tài liệu mà tập lệnh sử dụng để tạo email.
  • Dịch vụ thư: Tạo và gửi email có tên của người dùng và nội dung đã chọn.
  • Dịch vụ bảng tính: Thêm thông tin xác nhận vào trang tính Phản hồi biểu mẫu sau khi tập lệnh gửi email.

Điều kiện tiên quyết

Để sử dụng mẫu này, bạn cần đáp ứng các điều kiện tiên quyết sau:

  • Tài khoản Google (tài khoản Google Workspace có thể yêu cầu quản trị viên phê duyệt).
  • Trình duyệt web có quyền truy cập vào Internet.

Thiết lập tập lệnh

  1. Nhấp vào nút sau để tạo bản sao của bảng tính Gửi nội dung được tuyển chọn trong Trang tính. Dự án Apps Script cho giải pháp này được đính kèm với bảng tính:

    Tạo bản sao

  2. Trong bảng tính đã sao chép, hãy nhấp vào Tiện ích > Apps Script.

  3. Trong trình đơn thả xuống hàm, hãy chọn installTrigger.

  4. Nhấp vào Chạy.

  5. Khi được nhắc, hãy cho phép tập lệnh chạy. <<../_snippets/oauth.md>>

Quan trọng: Nếu bạn chạy installTrigger nhiều lần, tập lệnh sẽ tạo nhiều điều kiện kích hoạt, mỗi điều kiện kích hoạt sẽ gửi một email khi người dùng gửi biểu mẫu. Để xoá các điều kiện kích hoạt bổ sung và tránh gửi email trùng lặp, hãy nhấp vào biểu tượng Điều kiện kích hoạt . Nhấp chuột phải vào từng điều kiện kích hoạt bổ sung rồi nhấp vào Xoá điều kiện kích hoạt.

Chạy tập lệnh

  1. Chuyển lại bảng tính rồi nhấp vào Công cụ > Quản lý biểu mẫu > Chuyển đến biểu mẫu trực tiếp.
  2. Điền thông tin vào biểu mẫu và nhấp vào Gửi.
  3. Kiểm tra email của bạn để tìm email có đường liên kết đến nội dung mà bạn đã chọn.

Xem lại mã

Để xem lại mã Apps Script cho giải pháp này, hãy nhấp vào Xem mã nguồn:

Xem mã nguồn

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>

Người đóng góp

Mẫu này do Google duy trì với sự trợ giúp của các Google Developer Experts.

Các bước tiếp theo