1
votes

I have a Google Sheet where the Email & Name columns are auto-fill based on user submitted form. Also, I have 2 more columns where one column contain the list of giveaway code and another column is to act as an approval to send the email.

So for now I manage to create a button where when click it will send all emails with the giveaway code.

Now,

  1. How can I only send the email to the user that only has a value "y" in the Status column?
  2. Also, after sending the emails, the value "y" will changed to "d"? So that later, if I use the function again, it will only sending to the new users.

This is the sheet example https://docs.google.com/spreadsheets/d/1KkShktBnJoW9TmIzNsAuAJb6XslBrMwJGEJu7xeF1fk/edit?usp=sharing

This is the code

function sendArticleCountEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheetByName("Test1"));
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getRange("A2:E1000");
  var data = dataRange.getValues();
  for (i in data) {
    var rowData = data[i];
    var emailAddress = rowData[1];
    var timeStamp = rowData[0];
    var recipient = rowData[2];
    var code = rowData[3];
    var status = rowData[4];
    var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
    var subject = 'Here is your giveaway code!';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

/**
 * The event handler triggered when opening the spreadsheet.
 * @param {Event} e The onOpen event.
 */
function onOpen(e) {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [
    {name: 'Send Emails', functionName: 'sendArticleCountEmails'}
  ];
  spreadsheet.addMenu('Send Emails', menuItems);
}
1

1 Answers

1
votes

Just add an if statement like this:

function sendArticleCountEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheetByName("Test1"));
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getRange("A2:E1000");
  var data = dataRange.getValues();
  for (i in data) {
    var rowData = data[i];
    var emailAddress = rowData[1];
    var timeStamp = rowData[0];
    var recipient = rowData[2];
    var code = rowData[3];
    var status = rowData[4];
    var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
    var subject = 'Here is your giveaway code!';
    if (status == "y") {
        MailApp.sendEmail(emailAddress, subject, message);
        var actualRow = parseInt(i)+2;
        sheet.getRange(actualRow,5).setValue("d");
        }
  }
}