Let’s trigger a custom action after Google Form submission

Let’s image you are collecting responses with a Google Form. You may want to send automatically an email right the user submitted his responses.

You are on the right place. Let’s build this using a custom Google AppScript function and the Triggers feature.

Step 1: Open the Google Script Editor

→ Go to your form
→ Click the 3 dots on top right corner of your screen (see screenshot below)
→ Click Script Editor
→ You will switch to a new tab with an url looking like script.google.com/…

Script editor

Step 2: Create the empty function

It’s time to create a new function, which will be empty for the moment but don’t worry, we will write the functions’ code in step 4.

Just write the code below in the Code.gs file (you may already be in the file, it’s automatically created when you open the Script editor).

function onSubmit() {
// code to be added here later...
}

Step 3: Create & connect a new trigger

You have a create a new trigger and connect it to our empty function we just created.

→ Click the Triggers section in the left panel

→ Click the Add Trigger blue button in the right bottom corner on your screen

Now we will configure the new trigger to connect it with the empty function.

→ Choose which function = onSubmit
→ Deployment = Head
→ Event source = From form
→ Event type = On form submit
→ Failure notification = Notify me immediately

Step 4: Write the code of the function

Now you can go back to the Script editor by clicking Editor in the left panel.

In this example, I will show you how to send automatically an email to the user, right after he submitted the form.

Let me explain the code, line by line.

function onSubmit() {
  // Get active form & latest response
  var oForm = FormApp.getActiveForm();
  var aResponses = oForm.getResponses();
  var oResponse = aResponses[aResponses.length-1]; //latest response

  //  Find user email
  var userEmailAuto = oResponse.getRespondentEmail();
  // or...
  var userEmailManual = oResponse.getItemResponses()[5]; // imagine the user entenred his email in question number 6

  // User replies to insert in email
  var result = oResponse.getItemResponses()[2].getScore();

  // Send an email to the user
  MailApp.sendEmail({
    to: userEmailAuto, // or userEmailManual
    subject: "[RESULT] Following form submission",
    htmlBody: "Thanks for submitting the form.<br>" + 
              "Following your score (" + result + ") on question 3, you are allowed to join our team.<br>" +
              "🎉 Congrats"
  });

  // End of the script
  return;

}

Step 5: Test the execution

Two ways to test the code:

  1. You can debug and run it using the Script editor by clicking the Run or Debug button in the tool bar.
  2. Simply by submitting the form 😉

💌

Links

https://developers.google.com/apps-script/reference/forms/form-response
https://developers.google.com/apps-script/reference/forms/form-app

Any suggestion, anything to add? Write a comment!

Joey

Google Apps Script: Get current user email from a spreadsheet Add-On

Retrieve the current user email using App Script in your Spreadsheet Add-On is a little bit tricky. You can easily use the Session object to get it but in some cases, this object will return undefined.

Current user email using Session object

var userEmail = Session.getActiveUser().getEmail();

So, you need to find a workaround. The workaround could be to use the PropertyService object.

Current user email using PropertiesService object

var userEmail = PropertiesService.getUserProperties().getProperty('userEmail');

Why not, that’s another way to get it but not 100% too. If you want to secure it and combine another way to get it, you need to work with the sheet protection.

Current user email using spreadsheet protection

var protection = SpreadsheetApp.getActive().getRange('A1').protect();
protection.removeEditors(protection.getEditors());
var editors = protection.getEditors();
if (editors.length === 2) {
    var owner = SpreadsheetApp.getActive().getOwner();
    editors.splice(editors.indexOf(owner), 1);
}
userEmail = editors[0];
protection.remove();
PropertiesService.getUserProperties().setProperty('userEmail', userEmail);

Free to play

The full method, ready to use, capy-paste in your code and have fun:

function getCurrentUserEmail() {
    var userEmail = Session.getActiveUser().getEmail();
    if (userEmail === '' || !userEmail || userEmail === undefined) {
        userEmail = PropertiesService.getUserProperties().getProperty('userEmail');
        if (!userEmail) {
            var protection = SpreadsheetApp.getActive().getRange('A1').protect();
            protection.removeEditors(protection.getEditors());
            var editors = protection.getEditors();
            if (editors.length === 2) {
                var owner = SpreadsheetApp.getActive().getOwner();
                editors.splice(editors.indexOf(owner), 1);
            }
            userEmail = editors[0];
            protection.remove();
            PropertiesService.getUserProperties().setProperty('userEmail', userEmail);
        }
    }
    return userEmail;
}

Une Google Script pour créer des alertes e-mail sur leboncoin.fr

Le célèbre site de vente en ligne Leboncoin.fr ne propose pas l’option d’ “Alerte” sur son site. Dommage.

Par contre, en fouillant un peu sur le net, je suis tombé sur un script Google très intéressant et simple à mettre en place. Il permet d’envoyer des mails sur l’adresse et à la fréquence de votre choix.

Pré-requis : Avoir un compte Gmail pour profiter de Google Drive.

Etape 1 : Télécharger le fichier

La première étape consiste à copier le fichier tableur dans votre espace Google Drive. Cliquez simplement sur ce LIEN qui vous redirigera vers une page où il faut cliquer sur “Oui, créer une copie” (voir image ci-dessous) :

copiedocuementdriveVous voyez donc apparaître un tableur semblable à celui présenté ci-dessous. Ce tableur vous permet donc de gérer vos alertes (ajout, suppression, adresse des annonces etc…).

alertelbcmain

Etape 2 : Ajout d’une alerte

Pour ajouter une alterte, rendez-vous dans l’onglet “Données“.

Ajoutez un libellé dans la colonne A et collez le lien de la recherche leboncoin pour laquelle vous souhaitez être alerté dans la colonne B.

Laissez la cellule de la colonne C libre!

Etape 3 : Configuration (1/2)

La petite partie configuration démarre maintenant. Rien de bien compliqué, il s’agit d’initialiser le script.

Sélectionnez le menu “Lbc Alertes” puis cliquez sur “Setup email“.

Le script s’exécute puis vous demande votre adresse mail.

setupmail

Etape 4 : Configuration (2/2)

La dernière étape de la configuration consiste à initialiser la recherche.

Pour ça, sélectionnez le menu “Lbc Alertes (comme dans l’étape 3) et cliquez sur “Setup recherche“.

Le script s’exécute puis complète la cellule de la colonne C.

setuprecherche

Etape 5 : Fréquence des alertes

La toute dernière étape de ce tutoriel consiste à déterminer la fréquence des alertes.

Cliquez sur :

  • Outils
  • Editeur de scripts

Vous arrivez alors sur le code source du tableur :

codesourcealerte

Le déclencheur va être mis en place sur la fonction “lbc()“. C’est cette fonction qui permet d’envoyer des mails.

Cliquez sur :

  • Ressources
  • Déclencheurs du projet actuel
  • Choisissez la fonction “lbc()
  • Définissez l’échéance de déclenchement de la fonction (5minutes dans mon cas)

declencheurlbcalerte

Voilà, votre alerte est maintenant prête!

Une autre méthode que j’utilisais auparavant est bien pratique mais un peu compliquée à mettre en place puisqu’il faut utiliser une tâche Cron qui va “checker” l’arrivée de nouvelles annonces.

Je vous donne quand même le lien du code source pour ceux que ça peut intéresser: Lien GitHub (par Blount)