-1

I wanna set up a google script that will, with a press of a button, send one email to each user on the list. I have already set up the button, but I need help with merging all the values for one user in one mail instead of sending multiple emails with one value to the same person.

For example:

Table example

I basically need Rose to get one email which will have these items listed one below another:

pens
printer
sketchpad
ink and toners

and so on.

This is the script I have so far and there's a HTML body of the email as well:

function myFunction() {
  var name = 0;
  var email = 1;
  var objects = 2
  var emailTemp = HtmlService.createTemplateFromFile("body")
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
  var data = ws.getRange("A2:D" + ws.getLastRow()).getValues();
  data.forEach(function(row){
    emailTemp.fn = row[name];
    emailTemp.site = row[objects];
    var htmlMessage = emailTemp.evaluate().getContent();
    GmailApp.sendEmail(row[email], "No objects ordered", "Blabla",{htmlBody: htmlMessage})

  });
  
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
MM91
  • 23
  • 4

1 Answers1

0

A simple way to do it is through obtaining a reduced array of unique names / emails

This can be done e.g. with this function:

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}
  • Then you can loop through all unique values
  • Find all the rows where they are contained
  • Push the corresponding objects into an array
  • Proceed the array in "body.html" as desired.

Sample:

var unique = ws.getRange("A2:A" + ws.getLastRow()).getValues().flat().filter(onlyUnique);
  unique.forEach(function(person){
    var row_objects =[];  
    var mail = "";
    data.forEach(function(row){
      if(row[name] == person){
        row_objects.push(row[objects]);
        mail = row[email];
      }
    });
    Logger.log(row_objects);
      emailTemp.fn = person;
    emailTemp.site = row_objects;
    var htmlMessage = emailTemp.evaluate().getContent();
    GmailApp.sendEmail(mail, "No objects ordered", "Blabla",{htmlBody: htmlMessage})
  })  
ziganotschka
  • 25,866
  • 2
  • 16
  • 33
  • Hi, thanks for your help, however, I get the following error when I try to run the script: **ReferenceError: onlyUnique is not defined (line 8, file "Code")** for the following line: ```var unique = ws.getRange("A2:A" + ws.getLastRow()).getValues().flat().filter(onlyUnique);``` – MM91 Oct 15 '20 at 08:26
  • Did you insert the funciton definition into your script? That is `function onlyUnique(value, index, self) { return self.indexOf(value) === index; }` in addition to your already existing funciton `myFunction()`? You need to have both funcitons in your script. – ziganotschka Oct 15 '20 at 08:30
  • 1
    Crap, I forgot. :D Sorry, total beginner here. Thank you for your help! – MM91 Oct 15 '20 at 08:38