Skip to content

Instantly share code, notes, and snippets.

@senning
Created September 13, 2018 20:30
Show Gist options
  • Save senning/a0af54863c07eb47a10145feac067416 to your computer and use it in GitHub Desktop.
Save senning/a0af54863c07eb47a10145feac067416 to your computer and use it in GitHub Desktop.
Google Script to send out volunteer notifications using this spreadsheet: https://docs.google.com/spreadsheets/d/1nw1z3AXUhXaB-zY-e-nBvGdA0P4a4LRzhY6f5_pQ8HA/edit#gid=0
function sendEmails() {
//Get the active spreadsheet file (the one you've opened)
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Get the active sheet, and the cells you've highlighted in it
var dataSheet = ss.getActiveSheet();
var dataSelection = ss.getSelection();
var dataRange = dataSelection.getActiveRange();
//Get the template text from the sheet named "Copy". This script expects...
var templateSheet = ss.getSheetByName("Copy");
var emailTemplate = templateSheet.getRange('B3').getValue(); // the email text in B3
var subjectTemplate = templateSheet.getRange('B2').getValue(); // the subject line in B2
var senderName = templateSheet.getRange('B4').getValue(); // the sender name in B4
var bcc = templateSheet.getRange('B5').getValue(); //the BCC address in B5
//use the Google-provided getRowsData function to take each row of data and break it up in to columns, named with the column header
var objects = getRowsData(dataSheet, dataRange,2); // the "2" here tells the function that the column header is in row 2.
//for each row of data (each volunteer selected), do the following:
for (var i = 0; i < objects.length; i++){
var rowData = objects[i];
var emailText = fillInTemplateFromObject(emailTemplate, rowData); //Merge in the data for the email text
var emailSubject = fillInTemplateFromObject(subjectTemplate, rowData); //Merge in the data for the subject line
//Pack up the data in to the format that Google needs to send by GMail
var email = {
'to': rowData.email,
'subject': emailSubject,
'body': emailText,
'name': senderName
}
if(bcc){
email.bcc = bcc;
}
//send the email!
MailApp.sendEmail(email);
}
}
// Adapted from the Google version just to have more accurate variable names
function fillInTemplateFromObject(template, data){
// start with the template
var copy = template;
//find all the mail-merge target in the template
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
//for every mail-merge target found:
for (var i = 0; i < templateVars.length; ++i){
//set the value of the mail-merge target from the data
var variableData = data[normalizeHeader(templateVars[i])];
//update the template with the data for the target
copy = copy.replace(templateVars[i], variableData || '' );
}
//send the personalized copy back
return copy;
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial. - https://developers.google.com/apps-script/articles/mail_merge
//
//////////////////////////////////////////////////////////////////////////////////////////
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment