Skip to content

Instantly share code, notes, and snippets.

@Skoatpalace
Last active May 9, 2021 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Skoatpalace/1b59b6471820ae82c020b82f17de7bb4 to your computer and use it in GitHub Desktop.
Save Skoatpalace/1b59b6471820ae82c020b82f17de7bb4 to your computer and use it in GitHub Desktop.
Send email with template
/**
* This function generates a custom menu on the Spreadsheet Toolbar
*/
const onOpen = () => {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Send E-mails', 'startProcess')
.addToUi();
}
/**
* This function is triggered by the user when he runs the custom menu 'Send E-mails'
*/
const startProcess = () => {
const ss = SpreadsheetApp.getActiveSpreadsheet(); // Get the active Spreadsheet
const emailsSheet = ss.getSheetByName('Email List'); // Get the sheet 'Email List'
const listEmails = emailsSheet.getRange('A:A').getValues().flat(); // Get list of emails in simple Array
const recipients = emailsSheet.getRange(2,1,emailsSheet.getLastRow() - 1, emailsSheet.getLastColumn())
.getValues().filter(item => item[1]); // Get only rows where checkboxes are checked
const paramSheet = ss.getSheetByName('Params'); // Get the sheet 'Params'
const docIdTemplate = DocumentApp.openByUrl(paramSheet.getRange('B1').getValue()).getId(); // Get Docs ID from the url in cell 'B1'
const subject = paramSheet.getRange('B2').getValue(); // Get the subject for email in cell 'B2'
const date = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'dd/MM/yyyy') // Get the current date
DriveApp.getStorageUsed(); // unlock Drive Scope for using UrlFetchApp
const url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + docIdTemplate + "&exportFormat=html";
const param = {
method: "get",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true,
};
const html = UrlFetchApp.fetch(url, param).getContentText(); //Get the html from the Docs template
recipients.forEach(recipient => {
const email = recipient[0];
const body = formatBody_(html, email);
sendEmail_(email, subject, body);
const row = listEmails.indexOf(email);
emailsSheet.getRange(row + 1, 3, 1, 1).setValue(date);
});
ss.toast('All emails have been sent','✅ DONE');
}
/**
* This function sends a e-mail to the recipients selected
* @param {String} e-mail adress
* @param {String} e-mail subject
* @param {HTML} html body for e-mail
*/
const sendEmail_ = (email, subject, body) => {
MailApp.sendEmail(email, subject, null, {
htmlBody: body,
//noReply: true //this option is only allowed for Google Workspace accounts, not Gmail users
});
}
/**
* This function formats HTML by replacing placeholders
* @param {HTML} html body for e-mail
* @param {String} e-mail adress
* @return {HTML} html where placeholders has been replaced
*/
const formatBody_ = (html, email) => {
const fullName = formatFullName_(email); // get the full name from an email in the following format: firstName.lastName@mail.com
html = html.replace('#FULL_NAME', fullName); // replace placeholder
//html = html.replace('#OTHER_PLACEHOLDER', otherThing); // replace placeholder
//html = html.replace('#ANOTHER_PLACEHOLDER', anotherThing); // replace placeholder
return html;
}
/**
* This function extracts full name from an email
* @param {String} e-mail adress
* @return {String} full name
*/
const formatFullName_ = (email) => {
if (email.split('@')[0].indexOf('.') === -1) return '';
const fullName = email.split('@')[0].split('.');
return fullName.map(name => capitalize_(name)).join(' ');
}
/**
* This function convert the first letter of the word to uppercase
* @param {String} full name
*/
const capitalize_ = (name) => {
return name.charAt(0).toUpperCase() + name.slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment