ارسال محتوای انتخاب شده

سطح کدنویسی : مبتدی
مدت زمان : ۲۰ دقیقه
نوع پروژه : اتوماسیون با تریگر رویداد محور

اهداف

  • بفهمید که راه حل چه کاری انجام می‌دهد.
  • درک کنید که سرویس‌های Apps Script در این راهکار چه کاری انجام می‌دهند.
  • اسکریپت را تنظیم کنید.
  • اسکریپت را اجرا کنید.

درباره این راهکار

اگر انواع مختلفی از محتوا را می‌خواهید به مخاطبان خود ارائه دهید، می‌توانید به کاربران اجازه دهید با استفاده از فرم‌های گوگل، محتوایی را که از شما دریافت می‌کنند، انتخاب کنند. این راهکار به کاربران اجازه می‌دهد موضوعات مورد علاقه خود را انتخاب کنند و سپس محتوای انتخابی خود را به طور خودکار برای آنها ایمیل کنند.

نسخه آزمایشی ارسال محتوا با Google Forms و Gmail

چگونه کار می‌کند؟

این اسکریپت یک تریگر رویدادمحور نصب می‌کند که هر بار کاربر فرمی را ارسال می‌کند، اجرا می‌شود. با هر ارسال فرم، اسکریپت یک ایمیل از یک الگوی Google Docs ایجاد و ارسال می‌کند. ایمیل شامل نام کاربر و محتوای انتخابی او است. محتوایی که ارائه می‌دهید می‌تواند از هر نوعی باشد، تا زمانی که توسط یک URL ارجاع داده شود.

سرویس‌های اسکریپت برنامه‌ها

این راهکار از سرویس‌های زیر استفاده می‌کند:

  • سرویس اسکریپت - تریگر رویداد-محوری را نصب می‌کند که هر زمان کسی فرم را ارسال می‌کند، فعال می‌شود.
  • سرویس سند - الگوی سندنگاری را که اسکریپت برای ایجاد ایمیل از آن استفاده می‌کند، باز می‌کند.
  • سرویس ایمیل - ایمیل را با نام و محتوای انتخابی کاربر ایجاد و ارسال می‌کند.
  • سرویس صفحه گسترده - پس از ارسال ایمیل توسط اسکریپت، یک تأییدیه به برگه پاسخ‌های فرم اضافه می‌کند.

پیش‌نیازها

برای استفاده از این نمونه، به پیش‌نیازهای زیر نیاز دارید:

  • یک حساب گوگل (حساب‌های کاربری گوگل ورک‌اسپیس ممکن است نیاز به تأیید مدیر داشته باشند).
  • یک مرورگر وب با دسترسی به اینترنت.

اسکریپت را تنظیم کنید

  1. برای ایجاد یک کپی از صفحه گسترده ارسال محتوای گزینش‌شده، روی دکمه زیر کلیک کنید. پروژه Apps Script برای این راهکار به صفحه گسترده پیوست شده است.
    یک کپی تهیه کنید

  2. در صفحه‌گسترده کپی‌شده‌تان، روی افزونه‌ها > اسکریپت برنامه‌ها کلیک کنید.

  3. در منوی کشویی تابع، installTrigger را انتخاب کنید.

  4. روی اجرا کلیک کنید.

  5. وقتی از شما خواسته شد، اسکریپت را تأیید کنید. اگر صفحه رضایت OAuth هشدار « این برنامه تأیید نشده است» را نشان می‌دهد، با انتخاب Advanced > Go to {Project Name} (unsafe) ادامه دهید.

مهم : اگر installTrigger را بیش از یک بار اجرا کنید، اسکریپت چندین trigger ایجاد می‌کند که هر کدام هنگام ارسال فرم توسط کاربر، یک ایمیل ارسال می‌کنند. برای حذف triggerهای اضافی و جلوگیری از ایمیل‌های تکراری، روی Triggers کلیک کنید. روی هر trigger اضافی کلیک راست کرده و روی Delete trigger کلیک کنید.

اسکریپت را اجرا کنید

  1. به صفحه گسترده برگردید و روی ابزارها > مدیریت فرم > رفتن به فرم زنده کلیک کنید.
  2. فرم را پر کنید و روی ارسال کلیک کنید.
  3. ایمیل خود را برای دریافت لینک به محتوای انتخابی خود بررسی کنید.

کد را مرور کنید

برای بررسی کد Apps Script برای این راهکار، روی مشاهده کد منبع در زیر کلیک کنید:

مشاهده کد منبع

کد.gs

راهکارها/اتوماسیون‌ها/ثبت‌نام محتوا/کد.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();
}

مشارکت‌کنندگان

این نمونه توسط گوگل و با کمک متخصصان توسعه‌دهنده گوگل نگهداری می‌شود.

مراحل بعدی