Skip to content

Instantly share code, notes, and snippets.

@qmacro
Created January 2, 2014 13:50
Show Gist options
  • Save qmacro/8219400 to your computer and use it in GitHub Desktop.
Save qmacro/8219400 to your computer and use it in GitHub Desktop.
Calendar Inviter
CALENDAR = "Work";
EVENT_MATCH = /^SAP\s/;
GUEST_LIST = ['you-1@example.com', 'you-2@example.com'];
DATE_FROM = new Date('01 Jan 2014');
DATE_TO = new Date('31 Dec 2014');
FORCE_ADD = false;
function main() {
inviteMe(CALENDAR, DATE_FROM, DATE_TO, EVENT_MATCH, GUEST_LIST, FORCE_ADD);
}
/*
* Looks for allday events in a calendar. The events must match the given title.
* For each event found, add & invite guests if required
*/
function inviteMe(calendar, from, to, event_match, guest_list, force) {
// Assume only one calendar with the given name
var work_cal = CalendarApp.getCalendarsByName(CALENDAR)[0];
var events = work_cal.getEvents(from, to);
for (var i = 0, ii = events.length; i < ii; i++) {
var event = events[i];
var title = event.getTitle();
// Is the event an allday event with a title that matches?
if (event.isAllDayEvent() && title.match(event_match)) {
Logger.log("Event '%s' on %s", title, event.getStartTime());
event.setGuestsCanModify(true);
// Add and invite the guests if they're not already on the list
var current_guests = event.getGuestList().map(function(e) { return e.getEmail(); });
for (var g = 0, gg = guest_list.length; g < gg; g++) {
if (force || current_guests.indexOf(guest_list[g]) < 0) {
Logger.log("Adding guest '%s'", guest_list[g]);
addAndInvite(event, guest_list[g]);
}
}
}
}
}
/*
* GAS Calendar libs don't currently support sending invites directly
* when adding guests to an existing event (ticket open for 2.5 years!)
* so invite manually (ICS file via email).
*/
function addAndInvite(event, email) {
event.addGuest(email);
GmailApp.sendEmail(email, "Invite: " + event.getTitle(), "Please see attached calendar invitation", {
attachments: [{fileName:"invite.ics", content:generateIcs(event)}]
});
}
/*
* Generate a simple ICS file
*/
function generateIcs(event) {
return "BEGIN:VCALENDAR"
+ "\r\nPRODID:-//pipetree.com//qmacro//EN"
+ "\r\nVERSION:2.0"
+ "\r\nCALSCALE:GREGORIAN"
+ "\r\nMETHOD:REQUEST"
+ "\r\nBEGIN:VEVENT"
+ "\r\nDTSTART:" + Utilities.formatDate(event.getStartTime(), "GMT", "yyyyMMdd'T'HHmmss'Z'")
+ "\r\nDTEND:" + Utilities.formatDate(event.getEndTime(), "GMT", "yyyyMMdd'T'HHmmss'Z'")
+ "\r\nUID:" + event.getId()
+ "\r\nORGANIZER:" + event.getCreators()[0]
+ "\r\nSUMMARY:" + event.getTitle()
+ "\r\nLOCATION:" + event.getLocation()
+ "\r\nDESCRIPTION:" + event.getDescription()
+ "\r\nSEQUENCE:0"
+ "\r\nSTATUS:CONFIRMED"
+ "\r\nTRANSP:OPAQUE"
+ "\r\nEND:VEVENT"
+ "\r\nEND:VCALENDAR"
+ "\r\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment