I've been trying to set up an email notification for when I create a new announcement in my google site. I used a base code I found online but it isn't working for me. Here it is:
function myFunction() {
var url_of_announcements_page = "https://sites.google.com/announcements-page-link";
var who_to_email = "name@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 > ScriptProperties.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, "Announcement "+ann.getTitle(), ann.getTextContent()+"\n\n"+ann.getUrl(), options);
ScriptProperties.setProperty('last-update',updated);
}
}
}
}
function setup(){
ScriptProperties.setProperty('last-update',new Date().getTime());
}
}
The code seems to run with out any error message appearing. However, I do not receive the emails on the account I write in the code. I have given full permission so that the script can send the email from my account. It just doesn't seem to fulfil the task needed.
The google site I am using to write the announcements is still private and only I can see it, does that play a role in this code not working?
If you see any mistakes or have any idea what the issue is I would be happy to know.
You have written both the functions under myFunction
. You need to write it separately. Also ScriptProperties
API is deprecated, use PropertiesService
. Refer the below code. Hope this helps!
var url_of_announcements_page = "https://sites.google.com/announcements-page-link";
var who_to_email = Session.getActiveUser().getEmail();
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, "Announcement "+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());
}