Skip to content

Instantly share code, notes, and snippets.

@bencooper222
Created Dec 12, 2016
Embed
What would you like to do?
Easy Google Apps Script Secret Santa code given a spreadsheet with names in the B column and emails in the C column
var ss = SpreadsheetApp.getActiveSpreadsheet(); // this is meant to run inline google appsscript - you'll have to use a different get method if you don't want that
var sheet = ss.getSheets()[0]; // assumes sheet 1
var names = sheet.getRange(2,2,sheet.getLastRow()-1,2).getValues();
Logger.log(names);
if (names.length % 2 != 0) {
//alert("You must have an even number of names. You currently have " + names.length + " names.");
} else {
var arr1 = names.slice(), // copy array
arr2 = names.slice(); // copy array again
arr1.sort(function() { return 0.5 - Math.random();}); // shuffle arrays
arr2.sort(function() { return 0.5 - Math.random();});
while (arr1.length) {
var name1 = arr1.pop(), // get the last value of arr1
name2 = arr2[0] == name1 ? arr2.pop() : arr2.shift();
// ^^ if the first value is the same as name1,
// get the last value, otherwise get the first
// Logger.log(name1[1] + ' gets ' + name2[1]);
var message = "This is an autogenerated email. Your Secret Santa match is: " + name2[0] + ". You can see their address/wish list here: <include link to spreadsheet>";
GmailApp.sendEmail(name1[1], "Secret Santa", message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment