user11546973
user11546973

Reputation:

Send one Email to Multiple Addresses in Google Spreadsheet

I'm trying to create code that takes a line that contains the address and sends an email to all addresses in the same email. But my code sends the email only to the first address on the list and does not add the others.

function sendMail(){
 

 
  var sheetMail = SpreadsheetApp.getActiveSpreadsheet();
  var ecrvc = sheetMail.getSheetByName('List');
  
  var lastecrvc = ecrvc.getLastRow(); 
   
  //var email = [];
  var people = ",";
  var subject = "Hello All";
  var message = "This is a test";
  var email =  ecrvc.getRange("B2:B"+lastecrvc).getValues();
   

  
  for(var i = 9; i<lastecrvc; i++){
     var emailTo = ecrvc.getRange(i,2).getValues(); 
     email = emailTo + "@gmail.com"; 
     MailApp.sendEmail(email, subject, message)
      
    }
}

Upvotes: 1

Views: 322

Answers (1)

hexbioc
hexbioc

Reputation: 1606

If you'd like MailApp to send a single email to multiple recipients, you can use a comma separated email string as the first argument of MailApp.sendEmail. For example:

const emails = [ "[email protected]", "[email protected]" ]

// Join the emails into a single string separated by commas
const combinedEmails = emails.join() // "[email protected],[email protected]"

MailApp.sendEmail(combinedEmails, subject, message)

That ought to work. But do verify that you are correctly reading the email addresses from the sheet. If you aren't sure, you could share a sample sheet with identical arrangement as the one you are using.

Assuming that you are reading the email addresses from the spreadsheet correctly, you can modify your last for loop slightly to generate a combined email string, and then send the email outside the loop:

var emailsList = [];
for(var i = 9; i<lastecrvc; i++) {
  var emailTo = ecrvc.getRange(i,2).getValues(); 
  email = emailTo + "@gmail.com";
  emailsList.push(email);
}
var combinedEmails = emailsList.join();
MailApp.sendEmail(combinedEmails, subject, message);

Upvotes: 2

Related Questions