Skip to content

Instantly share code, notes, and snippets.

@oshliaer
Last active August 29, 2015 14:21
Show Gist options
  • Save oshliaer/975668e1aad347ebb1c2 to your computer and use it in GitHub Desktop.
Save oshliaer/975668e1aad347ebb1c2 to your computer and use it in GitHub Desktop.
YAMMPreparation prepares the line to send mail via YAMM (Yet Another Mail Merge) #gas
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('YAMM Preparation')
.addItem('Preparation', 'preparation')
.addItem('Set folder of Details', 'setFolderOfDetails')
.addToUi();
}
function preparation(){
try{
var new_data = [];
var active_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Email Sender');
var data = active_sheet.getDataRange().getValues().map(function(r){return r[0]});
var folderOfDetailsID = PropertiesService.getScriptProperties().getProperty('FolderOfDetailsID');
var folder = DriveApp.getFolderById(folderOfDetailsID);
var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
while (files.hasNext()) {
var file = files.next();
if(data.indexOf(file.getId()) == -1){
var sheet = SpreadsheetApp.open(file);
var email = sheet.getSheetByName('Email').getDataRange().getValues().toObjectVertical();
var details = sheet.getSheetByName('Details').getDataRange().getValues().toHTMLTable();
new_data.push([file.getId(), email['Email Address'] || '', email['Subject'] || file.getName(), email['Header'] || '', email['Footer'] || '', email['Attachment'] || '', details || '']);
}
Utilities.sleep(99);
}
if(new_data[0]){
active_sheet.getRange(active_sheet.getLastRow() + 1, 1, new_data.length, new_data[0].length).setValues(new_data);
SpreadsheetApp.flush();
}
}catch(e){
Logger.log(JSON.stringify(e));
}
}
function setFolderOfDetails(){
var folderOfDetailsID = PropertiesService.getScriptProperties().getProperty('FolderOfDetailsID');
if(folderOfDetailsID){
folderOfDetailsID = 'Now selected ' + folderOfDetailsID;
}else{
folderOfDetailsID = 'Please, enter ID';
}
var ui = SpreadsheetApp.getUi();
var prompt = ui.prompt('Set folder of Details', folderOfDetailsID, ui.ButtonSet.OK_CANCEL);
if(prompt.getSelectedButton() == ui.Button.OK){
PropertiesService.getScriptProperties().setProperty('FolderOfDetailsID', prompt.getResponseText());
}
}
<<Subject>>
<<Header>>
<<Data>>
<<Footer>>
<<Attachment>>
Array.prototype.toHTMLTable = function(){
var table = '<table>';
for(var i = 0; i < this.length; i++){
table += '<tr><td style="border-bottom:1pt solid gray;vertical-align:middle;text-align:center;">';
table += this[i].join('</td><td style="border-bottom:1pt solid gray;vertical-align:middle;text-align:center;">');
table += '</td></tr>';
}
table += '</table>';
return table;
}
Array.prototype.toObjectVertical = function(){
var obj = {};
for(var i = 0; i < this.length; i++){
obj[this[i][0]] = this[i][1];
}
return obj;
}
@oshliaer
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment