Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Created June 4, 2013 12:48
Show Gist options
  • Save mhawksey/5705633 to your computer and use it in GitHub Desktop.
Save mhawksey/5705633 to your computer and use it in GitHub Desktop.
Google Apps Script to send emails when an new Google Site Announcement is made (In response to https://plus.google.com/109310290306060614500/posts/JYMPQ2mLuEt )
/*
1. Set two variables below
2. Run > setup (twice, once to authenticate the script, second to actually run
3. Rescources > Current project trigger's and then click 'No triggers set up. Click here to add one now.'
You can accept the defaults to run emailAnnouncements() every hour
*/
var url_of_announcements_page = "https://sites.google.com/site/appsscripttemplates/home/announcetest"; // where your site page is
var who_to_email = "[email protected]" // who to send to (it can be a comma seperated list)
function emailAnnouncements(){
var page = SitesApp.getPageByUrl(url_of_announcements_page); // returns a page object
if(page.getPageType() == SitesApp.PageType.ANNOUNCEMENTS_PAGE){ // test if page object is announcement page
// get the last 10 announcements
var announcements = page.getAnnouncements({ start: 0,
max: 10,
includeDrafts: false,
includeDeleted: false});
announcements.reverse(); // reverse the result order so oldest first
for(var i in announcements) { // loop the individual announcements
var ann = announcements[i]; // just creating a little shortcut
var updated = ann.getLastUpdated().getTime(); // get when updated
if (updated > ScriptProperties.getProperty('last-update')){ // if greater than last update send email
var options = {}; // options used in MailApp
// create html body of the email using an announcement
options.htmlBody = Utilities.formatString("<h1><a href='%s'>%s</a></h1>%s", ann.getUrl(), ann.getTitle(), ann.getHtmlContent());
// send the email
MailApp.sendEmail(who_to_email, "Announcement "+ann.getTitle(), ann.getTextContent()+"\n\n"+ann.getUrl(), options);
// update the last email sent
ScriptProperties.setProperty('last-update',updated);
}
}
}
}
function setup(){
ScriptProperties.setProperty('last-update',new Date().getTime());
}
@Taumm
Copy link

Taumm commented Jul 25, 2017

If you have any issues with an email not sending when it should, I recommend that you reset the permissions. I had this issue with this code after a while and I was able to fix it by removing the permissions given and then giving them back again.

Hope this helps anybody that would have the same issue.

@MrShaunMcG
Copy link

Hi, this code it great and I've modded it already to suit my needs. However, I am struggling to change it so that the email sent does not include the body of the announcement. Any help on this would be much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment