선별된 콘텐츠 보내기

코딩 수준: 초급
기간: 20분
프로젝트 유형: 이벤트 기반 트리거를 사용한 자동화

목표

  • 솔루션의 기능을 이해합니다.
  • 솔루션 내에서 Apps Script 서비스의 기능을 이해합니다.
  • 스크립트를 설정합니다.
  • 스크립트를 실행합니다.

이 솔루션 정보

사용자에게 다양한 유형의 콘텐츠를 제공하려는 경우 Google Forms를 사용하여 사용자가 받는 콘텐츠를 선택하도록 할 수 있습니다. 이 솔루션을 사용하면 사용자가 관심 있는 주제를 선택한 후 선택한 콘텐츠를 자동으로 이메일로 보낼 수 있습니다.

Google Forms 및 Gmail로 콘텐츠를 전송하는 데모

사용 방법

스크립트는 사용자가 양식을 제출할 때마다 실행되는 이벤트 기반 트리거를 설치합니다. 양식을 제출할 때마다 스크립트는 Google 문서 템플릿을 사용하여 이메일을 만들고 보냅니다. 이메일에는 사용자 이름과 사용자가 선택한 콘텐츠가 포함됩니다. 제공하는 콘텐츠는 URL로 참조되는 한 어떤 유형이든 가능합니다.

Apps Script 서비스

이 솔루션은 다음 서비스를 사용합니다.

  • 스크립트 서비스–사용자가 양식을 제출할 때마다 실행되는 이벤트 기반 트리거를 설치합니다.
  • 문서 서비스 – 스크립트에서 이메일을 만드는 데 사용하는 문서 템플릿을 엽니다.
  • 메일 서비스–사용자 이름 및 콘텐츠 선택사항이 포함된 이메일을 만들어 전송합니다.
  • 스프레드시트 서비스: 스크립트에서 이메일을 보낸 후 양식 응답 시트에 확인 메시지를 추가합니다.

기본 요건

이 샘플을 사용하려면 다음과 같은 기본 요건이 필요합니다.

  • Google 계정 (Google Workspace 계정은 관리자 승인이 필요할 수 있음)
  • 인터넷 액세스가 가능한 웹브라우저

스크립트 설정

  1. 다음 버튼을 클릭하여 선별된 콘텐츠 보내기 스프레드시트의 사본을 만듭니다. 이 솔루션의 Apps Script 프로젝트는 스프레드시트에 첨부되어 있습니다.
    사본 만들기

  2. 복사된 스프레드시트에서 확장 프로그램 > Apps Script를 클릭합니다.

  3. 함수 드롭다운에서 installTrigger를 선택합니다.

  4. 실행을 클릭합니다.

  5. 메시지가 표시되면 스크립트를 승인합니다. OAuth 동의 화면에 확인되지 않은 앱입니다라는 경고가 표시되면 고급 > {프로젝트 이름}(으)로 이동(안전하지 않음)을 선택하여 계속 진행합니다.

중요: installTrigger를 두 번 이상 실행하면 스크립트는 사용자가 양식을 제출할 때 각각 이메일을 보내는 여러 트리거를 만듭니다. 추가 트리거를 삭제하고 중복 이메일을 방지하려면 트리거 를 클릭합니다. 각 추가 트리거를 마우스 오른쪽 버튼으로 클릭하고 트리거 삭제를 클릭합니다.

스크립트 실행

  1. 스프레드시트로 다시 전환하고 도구 > 양식 관리 > 실시간 양식으로 이동을 클릭합니다.
  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 Developer Experts의 도움으로 Google에서 관리합니다.

다음 단계