Email a group and not individual addresses with Google App Script

谁说我不能喝 提交于 2019-12-31 03:49:11

问题


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@company.com";

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@company.com by the name of the contact group I came out with this error:

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?

回答1:


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.



来源:https://stackoverflow.com/questions/45538689/email-a-group-and-not-individual-addresses-with-google-app-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!