Invia contenuti selezionati

Livello di programmazione: principiante
Durata: 20 minuti
Tipo di progetto: automazione con un trigger basato su eventi

Obiettivi

  • Comprendere cosa fa la soluzione.
  • Scopri cosa fanno i servizi Apps Script all'interno della soluzione.
  • Configura lo script.
  • Esegui lo script.

Informazioni su questa soluzione

Se hai vari tipi di contenuti da offrire al tuo pubblico, puoi consentire agli utenti di scegliere quali contenuti ricevere da te con Google Moduli. Questa soluzione consente agli utenti di selezionare gli argomenti che interessano loro, quindi invia automaticamente via email i contenuti scelti.

Demo dell'invio di contenuti con Moduli Google e Gmail

Come funziona

Lo script installa un trigger basato sugli eventi che viene eseguito ogni volta che un utente invia un modulo. A ogni invio del modulo, lo script crea e invia un'email da un modello di Documenti Google. L'email include il nome dell'utente e i contenuti che ha selezionato. I contenuti che offri possono essere di qualsiasi tipo, purché vi sia un riferimento a un URL.

Servizi Apps Script

Questa soluzione utilizza i seguenti servizi:

  • Servizio script: installa il trigger basato su eventi che si attiva ogni volta che qualcuno invia il modulo.
  • Servizio documenti: apre il modello di Documenti che lo script utilizza per creare l'email.
  • Servizio di posta: crea e invia l'email con il nome dell'utente e la selezione dei contenuti.
  • Servizio Fogli di lavoro: aggiunge una conferma al foglio Risposte del modulo dopo che lo script invia l'email.

Prerequisiti

Per utilizzare questo esempio, devi soddisfare i seguenti prerequisiti:

  • Un Account Google (gli account Google Workspace potrebbero richiedere l'approvazione dell'amministratore).
  • Un browser web con accesso a internet.

Configurare lo script

  1. Fai clic sul pulsante seguente per creare una copia del foglio di lavoro Invia contenuti selezionati. Il progetto Apps Script per questa soluzione è allegato al foglio di lavoro.
    Crea una copia

  2. Nel foglio di lavoro copiato, fai clic su Estensioni > Apps Script.

  3. Nel menu a discesa della funzione, seleziona installTrigger.

  4. Fai clic su Esegui.

  5. Quando ti viene richiesto, autorizza lo script. Se nella schermata per il consenso OAuth viene visualizzato l'avviso Questa app non è verificata, continua selezionando Avanzate > Vai a {Project Name} (non sicuro).

Importante: se esegui installTrigger più di una volta, lo script crea più trigger che inviano un'email ogni volta che un utente invia il modulo. Per eliminare gli attivatori aggiuntivi ed evitare email duplicate, fai clic su Attivatori . Fai clic con il tasto destro del mouse su ogni trigger aggiuntivo e fai clic su Elimina trigger.

Esegui lo script

  1. Torna al foglio di lavoro e fai clic su Strumenti > Gestisci modulo > Vai al modulo live.
  2. Compila il modulo e fai clic su Invia.
  3. Controlla la tua email per trovare un messaggio con i link ai contenuti che hai selezionato.

Esamina il codice

Per esaminare il codice Apps Script per questa soluzione, fai clic su Visualizza codice sorgente di seguito:

Visualizza codice sorgente

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();
}

Collaboratori

Questo esempio è gestito da Google con l'aiuto degli esperti Google.

Passaggi successivi