I have a script that creates a document from a template and updates the sheet with the FileID of the doc that was just create, this is working fine. What I am having trouble with is getting email to attach the file from the fileID column in my sheet.
Screen snip of Sheet
Here is the code of the email script without any scripting for adding the attachment. I have tried many things and just can't get the attachment piece to work. I also want to mention that this script is to be called from menu item and process all lines in the sheet with email addresses.
/**
function getData(sheetName) {
var data = SpreadsheetApp.getActive().getSheetByName(sheetName).getDataRange().getValues();
return data;
}
function renderTemplate(template, data) {
var output = template;
var params = template.match(/\{\{(.*?)\}\}/g);
params.forEach(function (param) {
var propertyName = param.slice(2,-2); //Remove the {{ and the }}
output = output.replace(param, data[propertyName] || "");
});
return output;
}
function rowsToObjects(rows) {
var headers = rows.shift();
var data = [];
rows.forEach(function (row) {
var object = {};
row.forEach(function (value, index) {
object[headers[index]] = value;
});
data.push(object);
});
return data;
}
/**
* Sends an email for each row.
*/
function sendEmails() {
var templateData = getData("Templates");
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var emailSubjectTemplate = templateData[1][0]; //Cell A2
var emailBodyTemplate = templateData[4][0]; //Cell A5
var emailData = getData("Data");
emailData = rowsToObjects(emailData);
emailData.forEach(function (rowObject) {
var subject = renderTemplate(emailSubjectTemplate, rowObject);
var body = renderTemplate(emailBodyTemplate, rowObject);
MailApp.sendEmail(rowObject["Email"], subject, body)
});
}