DPK
DPK

Reputation: 1

Google App Script - Send Single Email for FOR loop instead of multiple repetitive Emails

  1. This code is sending multiple emails with repetition because of for loop, i wanted it to send single email

function Buy() {
  var ss=SpreadsheetApp.getActive();
 var sheet=ss.getSheetByName("Buy");  
  var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues();
  var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues();
  var results=[];

for(var i=0;i<Cvalues.length;i++){

if(Cvalues[i][0]<=-3){
      results.push(" "+ Avalues[i]);
      results.push("Price "+ Cvalues[i]);
      MailApp.sendEmail('[email protected]', 'Buy Alert',results.join("\n")); 
    }
  }

}
  1. This code is sending email when if condition is met or not met (blank alert)
function Buy() {
  var ss=SpreadsheetApp.getActive();
  var sheet=ss.getSheetByName("Buy");  
  var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues();
  var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues();
  var results=[];

for(var i=0;i<Cvalues.length;i++){

if(Cvalues[i][0]<=-3){
      results.push(" "+ Avalues[i]);
      results.push("Price "+ Cvalues[i]);
    }
  }

MailApp.sendEmail('[email protected]', 'Buy Alert',results.join("\n")); 

}

Send Single Email for FOR loop instead of multiple repetitive Emails, what other alternatives to achieve this efficiently without receiving multiple repetitive emails and blank email alerts

Upvotes: 0

Views: 49

Answers (1)

Mart&#237;n
Mart&#237;n

Reputation: 10187

You could add a new conditional evaluating if "results" contains values in your 2nd option code:

if(results.length>0){
  MailApp.sendEmail('[email protected]', 'Buy Alert',results.join("\n")); 
}

Upvotes: 1

Related Questions