Alvim Silva
Alvim Silva

Reputation: 1

Create mailing list for sendmail

I would like to create a list of emails, which are listed in the column of a sheets.

how can I do this?

example:

column A email 1 email 2 email 3

mailling = column A

MailApp.sendEmail({
     to: mailling,
     subject: "test",
     body: "Test message",

Upvotes: 0

Views: 218

Answers (2)

Francisco Lozada
Francisco Lozada

Reputation: 21

I think you should check the documentation of the class like suggested in the comments, it has really good features that can improve the way you email. Anyway, here is an example that can help you.


    function sendMail() {
    
    //Each numer means the column of the sheets thats going to grab the value
      var first = 0;
      var second = 1;
      var third = 2;
      
    //In the Column D must have the emails  
      var fourth =3;
      
    //Specifies the HTML document that going to give the structure of the email  
      var emailTemp = HtmlService.createTemplateFromFile("email");
      
    //Tells wich is the sheet to take information
    //in this case the sheets name is "Data Base"
      var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data Base");
      
    //Gives the range of the columns that the information is going to be  
      var data = ws.getRange("A1:E" + ws.getLastRow()).getValues();
      
    //This is an optional filter in the Column F so you can filter wich rows to run
      data = data.filter(function(r){ return r[5] == true });
      
    //To use the variables in between the HTML file your going to use the value after "emailTemp." as <?= fr ?>
      data.forEach(function(row){
        
        emailTemp.fr = row[first];
        emailTemp.se = row[second];
        emailTemp.th = row[third];
        var htmlMessage = emailTemp.evaluate().getContent();
        GmailApp.sendEmail(row[fourth], "HEEERE GOES THE SUBJECT OF THE EMAIL", "Your email doesn't support HTML.", {name: "Email", htmlBody: htmlMessage})
       });

Here I used a html template to send emails with variables extracted from other columns. You can check out this github

Upvotes: 0

Cooper
Cooper

Reputation: 64032

if your emails are in column A starting from row 2:

function getEmails() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const emails = sh.getRange(2,1,sh.getLastRow() - 1, 1).getValues().flat();
  return emails.join(',');
}

function sendEmails() {
  MailApp.sendEmail({to: getEmails(),subject: "test",body: "Test message"});
}

Upvotes: 0

Related Questions