Taum
Taum

Reputation: 341

Email a group and not individual addresses with Google App Script

I am working on an email notification script for my Google Site, I have tested it and it works fine, here is the code:

var url_of_announcements_page = "https://sites.google.com/a/announcements"; 
var who_to_email = "[email protected]";

function emailAnnouncements(){
  var page = SitesApp.getPageByUrl(url_of_announcements_page);
  if(page.getPageType() == SitesApp.PageType.ANNOUNCEMENTS_PAGE){ 

    var announcements = page.getAnnouncements({ start: 0,
                                               max: 10,
                                               includeDrafts: false,
                                               includeDeleted: false});
    announcements.reverse();                                    
    for(var i in announcements) { 
      var ann = announcements[i]; 
      var updated = ann.getLastUpdated().getTime(); 
      if (updated > PropertiesService.getScriptProperties().getProperty("last-update")){ 
        var options = {}; 

        options.htmlBody = Utilities.formatString("<h1><a href='%s'>%s</a></h1>%s", ann.getUrl(), ann.getTitle(), ann.getHtmlContent());

        MailApp.sendEmail(who_to_email, "Notification - '"+ann.getTitle()+"'", ann.getTextContent()+"\n\n"+ann.getUrl(), options);

        PropertiesService.getScriptProperties().setProperty('last-update',updated);
      }
    }
  }
}

function setup(){
 PropertiesService.getScriptProperties().setProperty('last-update',new Date().getTime());
}  

The only issue is that I wish to have multiple people receive this email. I know it is possible to add them one by one using a coma after each email address. However, this is a lot of maintenance and I wanted to switch it to a Gmail Contact Group to make maintenance quicker.

I tried replacing the email address by a Contact Group that I created on Gmail. I had called it Test, and when I replaced [email protected] by the name of the contact group I came out with this error:

enter image description here

I have looked online and I can't find something that helps me specifically with my situation. So I have two questions:

  1. Is there a way to change the code to make the Gmail Contact Group work?
  2. If not, is there something else than a Gmail Contact Group that I can use for this?

Upvotes: 2

Views: 2403

Answers (1)

James D
James D

Reputation: 3142

You need to get the email address to an array first. Use the contacts app to get the Test group and then loop through all the contacts to get their addresses.

var emails = []; 
var contacts = ContactsApp.getContactGroup('Test').getContacts();
 for(var i in contacts){
    emails.push(contacts[i].getPrimaryEmail());
   }

Then use the emails variable in the send to or bcc parameter as Cooper suggested.

Upvotes: 4

Related Questions