Google App Scripts - Auto Sending Emails (specific issue delete row and appendRowL) - google-apps-script

I'm trying to use Google App Scripts to send HTML emails for me that I wrote. My code works to the point where I can get the e-mails to send however as you'll see in my code I have 4 different templates that I want to send . . As you'll see I have some code to change the template by 1 to find the right template and dateMath to increase the date for the next e-mail to send.
The issue that I'm running across right now is with deleteRow and appendRow. I have 2 users that I'm trying to e-mail and when I run the code deleteRow and appendRow replaces one of the users with the other. It'll make more sense with my screen shots. Any insight here?
Before Script
After Script
function sendEmails(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getValues();
var today = Utilities.formatDate(new Date(), "MDT", "dd/MM/yyyy");
for(var i = 1; i<data.length; i++){
if(data[i][3] !== ""){ //skip if is empty
if(isValidDate(data[i][3])){ //skip if isn't a valid date
var formattedDate = Utilities.formatDate(data[i][3], "MDT", "dd/MM/yyyy");
if(formattedDate == today){ //send email if checkin date is today
if(data[i][4] == 1) {
var template = HtmlService.createTemplateFromFile('Template1');
} else if(data[i][4] == 2){
var template = HtmlService.createTemplateFromFile('Template2');
} else if(data[i][4] == 3){
var template = HtmlService.createTemplateFromFile('Template3');
} else {
var template = HtmlService.createTemplateFromFile('Template4');
}
var email = data[i][2];
var firstName = data[i][0];
var lastName = data[i][1];
template.firstName = firstName;
var subject = "Your Next Steps ";
var bcc = "spencer#kwwestfield.com";
var message = template.evaluate();
GmailApp.sendEmail(email,
subject,
message.getContent(), {
htmlBody: message.getContent(),
bcc: bcc
});
//change the template
//delete the row
sheet.deleteRow(i+1);
//add the row again
var newTemplate = data[i][4] + 1;
var newSend = dateMath(data[i][3], 8);
sheet.appendRow([firstName, lastName, email, newSend, newTemplate]);
}
}
}
}
}
/**
* Does math on dates
* Triggered from functions
* Input: date = the orginal date, d = +- number of days
* Output: a new date
*/
function dateMath(date,d){
var result = new Date(date.getTime()+d*(24*3600*1000));
return result
}
/**
* Figures out if is a data
* Triggered from functions
* Input: d: any
* Output: boolean
*/
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" ){
return false;
} else {
return true;
}
}

Because you're deleting a row, the i value no longer corresponds to the same range. For example, you have an array with 5 elements:
[A, B, C, D, E]
If you delete element 0, you'll get
[B, C, D, E]
Now you increment your iterator so i++; // i = 1 and so the next value that you'll operate on is not "B", but instead "C".
You can try yourself by running this
function test() {
var letters = ["A", "B", "C", "D", "E"];
for (var i=0; i<letters.length; i++) {
Logger.log("i : " + i + " || Letter: " + letters[i]);
letters.shift();
}
}
To fix your code, add a row variable that is independent of your array iterator i.
function sendEmails(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getValues();
var today = Utilities.formatDate(new Date(), "MDT", "dd/MM/yyyy");
var row = 2; // Starting at row 2
for(var i = 1; i<data.length; i++){
if(data[i][3] !== ""){ //skip if is empty
if(isValidDate(data[i][3])){ //skip if isn't a valid date
var formattedDate = Utilities.formatDate(data[i][3], "MDT", "dd/MM/yyyy");
if(formattedDate == today){ //send email if checkin date is today
if(data[i][4] == 1) {
var template = HtmlService.createTemplateFromFile('Template1');
} else if(data[i][4] == 2){
var template = HtmlService.createTemplateFromFile('Template2');
} else if(data[i][4] == 3){
var template = HtmlService.createTemplateFromFile('Template3');
} else {
var template = HtmlService.createTemplateFromFile('Template4');
}
var email = data[i][2];
var firstName = data[i][0];
var lastName = data[i][1];
template.firstName = firstName;
var subject = "Your Next Steps ";
var bcc = "spencer#kwwestfield.com";
var message = template.evaluate();
GmailApp.sendEmail(email,
subject,
message.getContent(), {
htmlBody: message.getContent(),
bcc: bcc
});
//change the template
//delete the row
sheet.deleteRow(row);
row--; // Deleted a row
//add the row again
var newTemplate = data[i][4] + 1;
var newSend = dateMath(data[i][3], 8);
sheet.appendRow([firstName, lastName, email, newSend, newTemplate]);
}
}
}
row++; // Go to the next row
}
}

Related

How to send single email from spreadsheet to people whom names are repeated

I have a google spreadsheet of the following format. https://docs.google.com/spreadsheets/d/1-GwqlPofB7P4g2o3DbZKtdu5pMXvnQdgRDlhoyVijeg/edit?usp=sharing
I want to send mail to individual owners (people) including 2 tables, 1st table to include all the actionable that are not completed and the close that has been crossed, and the 2nd table to include all the actionable that are yet to be completed but closed date has not been crossed.
For eg :- Expected mail to be sent to Name 1 is
Hi, following tasks are delayed:
Table of showing tasks which are delayed
------ |||including Tasks 3 and Task 9|||
The following tasks are yet to be completed:
table showing tasks which are not completed but also not delayed.
--------------|||Task 1 and Task 6|||
I have created an app-script to send email to a person when only 1 persons task are mention are 1 sheet. I am not able to do so with multiple people being mentioned in the same sheet multiple times.
function SendMail() {
// GETTING VALUES FROM SPREADSHEET
//Selecting the sheet
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("name");
var startRow = 4; // First row of data to process
var numRows = sheet.getLastRow()-3; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn()); // Selecting the range of data
var data = dataRange.getValues(); // Get all values in the range.
//Creating Today's Date
// Date String in required format
var today_string = Utilities.formatDate(new Date(), 'GMT+05:30', 'MM/dd/yyyy');
var today = new Date(today_string)
today.setHours(0,0,0,0)
//Logger.log(today);
//Creating an Empty Array in which values will be added
var delayed = [];
var pending =[];
// Initiating For Loop
for (var i = 0; i < data.length; ++i) {
var row = data[i]; // Creating all the rows
var close_date_string = Utilities.formatDate(new Date(row[4]),'GMT+05:30','MM/dd/yyyy'); // Close Date String
var close_date = new Date(close_date_string) //Close_Date, (Date Value)
close_date.setHours(0,0,0,0)
// Putting condition to fill the delayed array
if (close_date < today && row[5].toString().match("Completed") != "Completed") {
var delayed_text = {};
delayed_text.actionable = row[1];
delayed_text.start_date = row[3] ?
Utilities.formatDate(new Date(row[3]),'GMT+05:30','MMMM dd, yyyy') :
"-";
delayed_text.close_date = row[4] ?
Utilities.formatDate(new Date(row[4]),'GMT+05:30','MMMM dd, yyyy') :
"-";
delayed.push(delayed_text)
}
// Putting conditions to fill the Pending array
if (close_date >= today && row[5].toString().match("Completed") != "Completed") {
var pending_text = {};
pending_text.actionable = row[1];
pending_text.start_date = row[3] ?
Utilities.formatDate(new Date(row[3]),'GMT+05:30','MMMM dd, yyyy') :
"-";
pending_text.close_date = row[4] ?
Utilities.formatDate(new Date(row[4]),'GMT+05:30','MMMM dd, yyyy') :
"-";
pending.push(pending_text)
}
}
//Getting HTML Table for Delayed
var delayed_template = HtmlService.createTemplateFromFile("Delayed.html");
delayed_template.delayed = delayed;
var delayed_table = delayed_template.evaluate().getContent();
//Getting HTML Table for pending
var pending_template = HtmlService.createTemplateFromFile("Pending.html");
pending_template.pending = pending;
var pending_table = pending_template.evaluate().getContent();
//Logger.log(pending_table)
//Making an empty variable message to add tables to it on basis of condition
var message = ""
// Making conditions to add table to message content
if (Object.keys(delayed).length && Object.keys(pending).length) {
message = ("Hi Sir,\n" + delayed_table + pending_table) ;
} else if (Object.keys(delayed).length) {
message = ("Hi Sir,\n" + delayed_table) ;
} else if (Object.keys(pending).length) {
message = ("Hi Sir,\n" + pending_table) ;
} else {
message = "" ;
}
// SENDING MAIL
if (message) {
//Logger.log("sent")
MailApp.sendEmail({
to: "email",
subject: "Actionable Status",
htmlBody: message
})
} // closing if statement
} //closing SendEmail
How to create an apps-cript that can work with the above sheet?
Try this
function sendEmails() {
var [, ...rows] = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2').getDataRange().getValues()
rows.forEach(r => sendEmail(r[0], r[1]))
}
function sendEmail(name, email) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
var [headers, ...rows] = sheet.getDataRange().getValues();
var today = new Date()
//delayed
var delayed = rows.filter(r => (getAllNames(r[3]).indexOf(name) != -1 && r[5] != 'Completed' && r[7] < today))
delayed.forEach(function (r) {
r[6] = Utilities.formatDate(new Date(r[6]), 'GMT+05:30', 'MMMM dd, yyyy')
r[7] = Utilities.formatDate(new Date(r[7]), 'GMT+05:30', 'MMMM dd, yyyy')
})
//pending
var pending = rows.filter(r => (getAllNames(r[3]).indexOf(name) != -1 && r[5] != 'Completed' && r[7] >= today))
pending.forEach(function (r) {
r[6] = Utilities.formatDate(new Date(r[6]), 'GMT+05:30', 'MMMM dd, yyyy')
r[7] = Utilities.formatDate(new Date(r[7]), 'GMT+05:30', 'MMMM dd, yyyy')
})
//message
var message = (delayed.length > 0 ? tableHTML([headers], delayed) : '') +
'<br><br>' + (pending.length > 0 ? tableHTML([headers], pending) : '')
if (delayed.length > 0 || pending.length > 0) {
MailApp.sendEmail({
to: email,
subject: "Actionable Status",
htmlBody: message
})
}
}
function tableHTML(headers, data) {
var tableformat = 'cellspacing="2" cellpadding="2" border="1" style="width:100%;border-collapse:collapse;border:1px solid #ccc';
var header = headers.map(h => '<tr><th>' + h.join('</th><th>') + '</th></tr>')
var rows = data.map(h => '<tr><td>' + h.join('</td><td>') + '</td></tr>')
return '<table ' + tableformat + ' ">\n' + header.join('\n') + rows.join('\n') + '</table>'
}
function getAllNames(coop) {
var names = []
coop.split('&').forEach(function (name) {
names.push(name.trim())
})
return (names.sort())
}

Google Sheets - Send email based on cell matching True or False

I don't work with Google Sheets very often and mainly deal with Google Form's script editor. We have created a database from various forms that fill into one spreadsheet and I would like to send email notifications to specific managers based on the recent row update, which would update from a form submission. Here is what I was trying to get it to do:
if cell in Column P matches to "FALSE":
send email
set the recipient field as "director1#gmail.com" if cell in Column J matches to the word "Building 1"
set the CC field as "manager1#gmail.com" if the cell in Column I matches to the word "Department 1"
if Column P matches to "TRUE", then it doesn't have to do anything
function triggerOnEdit(e)
{
alertManagers(e);
}
function checkClearance(e)
{
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName("Calculations");
var value = sheet.getRange("P:P").getValue();
var range = sheet.getRange(1, 1, sheet.getLastRow(), 1); //understands spreadsheet
if(range.getColumn() <= 16 &&
range.getLastColumn() >=16 )
{
var edited_row = range.getRow();
var approval = SpreadsheetApp.getActiveSheet().getRange(edited_row,16).getValue();
if(approval == 'FALSE')
{
return edited_row;
}
}
return 0;
}
function alertManagers(e)
{
var clearance_row = checkClearance(e);
if(clearance_row <= 0)
{
return;
}
sendEmailByRow(clearance_row);
}
function sendEmailByRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row,1,row,16).getValues();
var row_values = values[0];
var mail = composeAlertEmail(row_values);
var manageremail='test#gmail.com';
//Uncomment this line for testing
//SpreadsheetApp.getUi().alert(" subject is "+mail.subject+"\n message "+mail.message);
MailApp.sendEmail(manageremail,mail.subject,mail.message);
}
function composeAlertEmail(row_values)
{
var name = row_values[6];
var email = "test#gmail.com";
var message = "Good day, \n The following employee does not have clearance to enter the building: "+name+
" email "+email;
var subject = "Employee Not Cleared: "+name+" "
return({message:message,subject:subject});
}
Does this seem possible? I know I am probably far off from a solution, but thanks if anyone can help in advance!
Solution:
Here is what you are looking for:
function triggerOnEdit(e) {
sendEmails(e)
}
function sendEmails(e){
const row = e.range.getRow();
const col = e.range.getColumn();
const as = e.source.getActiveSheet();
const subject = "This is the subject of the email";
const body = "This is the body of the email";
const to = "director1#gmail.com";
const cc = "manager1#gmail.com";
if(as.getName() == "Calculations" && col == 16 && as.getRange(row,col).getDisplayValue() == "FALSE") {
if (as.getRange(row,10).getValue()=="Building 1"){
if(as.getRange(row,9).getValue()=="Department 1"){
MailApp.sendEmail({to:to ,subject: subject,body:body,cc:cc});
}
else {
MailApp.sendEmail({to: to,subject: subject,body:body});
}
}
}
}
I assume that if column J does not match Building 1 which means there is no recipient, the email won't be sent.
Don't forget to add triggerOnEdit(e) to the current project's trigger:

Email should NOT be sent when NO data in the selected sheet

I have a script which pulls data from a defined tab name 'Master' in Google sheet, which is then sending an email triggering at a specific time.
My problem is I don't want script to send blank email if the table in 'Master' is empty. Script should stop sending email.
Otherwise keeps triggering email on mentioned time.
Can anyone please share their insight on this.
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Master");
var range = sheet.getDataRange();
var recipient = 'email#gmail.com'
var subject = 'Stock Report'
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
var schedRange = sheet.getRange("A1:L21");
var body = '<div style="text-align:center;display: inline-block;font-family: arial,sans,sans-serif">'
body += '<H1>'+ 'Low Stock Report ' +'</H1>';
body += '<H2>'
body += getHtmlTable(schedRange);
body += '</div>';
GmailApp.sendEmail(recipient, subject, "Requires HTML", {htmlBody:body})
//End sendNotification
}
How to check if the table is not empty
If your table is var schedRange = sheet.getRange("A1:L21"); you can check either its empty by retrieving its values and send it only in case a non-empty value is found.
You can implement a boolean variable - as soon as the first non-empty value is found in the table - it will be set to true and an email will be sent.
Sample:
function sendEmail() {
...
var schedRange = sheet.getRange("A1:L21");
var values = schedRange.getValues();
var send = false;
for (var i = 0; i < values.length; i++){
for (var j = 0; j < values[0].length; j++){
var value = values[i][j];
if (value !="" && value !=" "){
return send = true;
}
}
}
if (send == true){
var body = '<div style="text-align:center;display: inline-block;font-family:
...
GmailApp.sendEmail(recipient, subject, "Requires HTML", {htmlBody:body})
}
}
You can also do something like this:
var schedRange = sheet.getRange("A1:L21");
var values = schedRange.getValues();
if (values.flat(2).length>0) {
//Send
var body = '<div style="text-align:center;display: inline-block;font-family:
...
GmailApp.sendEmail(recipient, subject, "Requires HTML", {htmlBody:body})
}
Thanks to the fact that flat() will make a 2D array into a simple array, removing empty elements, we can use it to basically remove all blank values from the array, effectively checking if it's empty or not.
After applying sample code I am not getting email, I have tried both ways with and without data in Master Sheet but no email.I am not sure if i am doing the right way.
Sample:
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Master");
var range = sheet.getDataRange();
var recipient = 'alislife87#gmail.com'
var subject = 'Stock Report'
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
var schedRange = sheet.getRange("A1:L21");
var values = schedRange.getValues();
var send = false;
for (var i = 0; i < values.length; i++){
for (var j = 0; j < values[0].length; j++){
var value = values[i][j];
if (value !="" && value !=""){
return send = true;
}
}
}
if (send == true){
var body = '<div style="text-align:center;display: inline-block;font-family:
arial,sans,sans-serif">'
body += '<H1>'+ 'Low Stock Report ' +'</H1>';
body += '<H2>'
body += getHtmlTable(schedRange);
body += '</div>';
GmailApp.sendEmail(recipient, subject, "Requires HTML", {htmlBody:body})
}
}

Need help iterating down a column in google sheets and sending out an email based on each individual value in the cells

I am guessing this is a simple thing to do but I am not sure how to do it. I have a google script that I want to run daily that checks the values of cells within one column in google sheets individually and sends an email if the value drops below a certain threshold.
What I have so far is
function sendEmail() {
var data = SpreadsheetApp.getActiveSheet().getRange('E2').getValue();
if (data < 300){
var emailAddress = "emailaddress#email.com";
var message = "test body";
var subject = "test subject";
MailApp.sendEmail(emailAddress, subject, message);
}
}
EDIT
Here is where I am now. It works except for pulling the emails from the cells.
function sendEmail() {
function letThemKnow(num) { //This creates a function named letThemKnow which is passed the variable num from the if/else statements
var emailAddress = email[i]; //Sets the variable to the email address of
var message = "Greetings! This is an automated message to let you know your license for " + software[i] + " expires in " + num + " days.";
var subject = "Impending expiration of " + software[i];
MailApp.sendEmail(emailAddress, subject, message);
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet();
var lastRow = sh.getLastRow();
var data = sh.getRange(2, 5, lastRow, 1).getValues();
var software = sh.getRange(2, 1, lastRow, 1).getValues();
var email = sh.getRange(2, 7, lastRow, 1).getValues();
for (i = 0; i <= email.length; i++) {
for (i = 0; i <= software.length; i++) {
for (i = 0; i <= data.length; i++) {
var num = parseInt(data[i]);
if (num == 30) {
letThemKnow(num)
} else if (num == 14) {
letThemKnow(num)
} else if (num <= 7) {
letThemKnow(num)
}
}
} //
}
} //
Your for loop is starting at '0' and ending at '0'. Try this:
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet();
var lastRow = sh.getLastRow();
var data = sh.getRange(2,5,lastRow,1).getValues();
for (i=0;i <= data.length;i++){
var num = parseInt(data[i]);
if (num < 300) {
var emailAddress = "email#email.com";
var message = "test body";
var subject = "test subject";
MailApp.sendEmail({
name: "Your Name",
to: emailAddress,
subject: subject,
htmlBody: message
});
}
}
}
If the email is the same every time, you should probably define those variables outside the loop.

Google Form Send Email to Owner after Response Submission

I am just starting Google Forms. I need to email the form owner (myself and some others) a response as soon the the user submit the data. I need the data in the email which would include fields and their values that were submitted by the user as soon as they submit the form.
I am unable to use add-on as per my google account settings via my employer where add-on are blocked.
I am exploring app scripts but with little success as I am very new. As there some sample codes to help me get started with create a basic script to send email.
I have the following Code:
function sendFormByEmail(e)
{
var email = "ownersemail#host.ca";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
var subject = "New Hire: ";
for(var i in headers)
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
subject += e.namedValues[headers[2]].toString() + " - starts " + e.namedValues[headers[15]].toString();
MailApp.sendEmail(email, subject, message);
}
Then I added this script in the form trigger like so:
I tried submitting the form but nothings heppens. How do I know that the script ran or there was a problem?
If I try to run this in the script editor :
It gives me an error :
TypeError: Cannot call method "getRange" of null. (line 7, file "Code")
Update
I tested the email functionality and it worked. So the problem has to be in Spread Sheet value retrieval.
function sendFormByEmail(e)
{
var email = "ownersemail#host.ca";
MailApp.sendEmail(email, "Test", "Test");
}
I also created a excel file on my google drive that holds these response from google form
Final Solution
function testExcel() {
var email = "ownersemail#host.ca";
var s = SpreadsheetApp.openById("GoogleDocsID");
var sheet = s.getSheets()[0];
var headers = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0];
var datarow = sheet.getRange(sheet.getLastRow(),1,1,sheet.getLastColumn()).getValues()[0];
var message = "";
for(var i in headers)
{
message += "" + headers[i] + " : " + datarow[i] + "\n\n";
//Logger.log(message);
}
MailApp.sendEmail(email, "Submitted Data Test", message);
}
Here is a shell for you to start with. I use this code for a very similar reason. This shell includes creating a Google Doc from template and adding data from the sheet into that Doc. You can use similar methods to set variables and add them into the email. I use an html template file(s) to manage exactly what is being sent each time.
The merge portion checks through the Doc (you can set it to look through html file) and finds my tags using RegEx; structed as so: <<columnHeader>>. In this way, You have a consistent template that replaces those tags with the data, in that column, for that row. Modify to your needs as you see fit.
This also displays the progress of the merge. That way, it won't repeat your emails/ merge.
NOTE: There are several data points missing as I removed the personal information; it won't run straight from this sample. You will have to add your document IDs, correct for variable placement, etc.
function mergeApplication() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("");
var formSheet = ss.getSheetByName("");
var lastRow = formSheet.getLastRow();
var lastColumn = sheet.getMaxColumns();
function checkAndComplete() {
var urlColumn = lastColumn;
var checkColumn = (urlColumn - 1);
var checkRange = sheet.getRange(2, checkColumn, (lastRow - 1), 1);
var check = checkRange.getBackgrounds();
var red = "#ff0404";
var yellow = "#ffec0a";
var green = "#3bec3b";
for (var i = 0; i < check.length; i++) {
if (check[i] == green) {
continue;
} else {
var statusCell = sheet.getRange((i+2), checkColumn, 1, 1);
var urlCell = sheet.getRange((i+2), urlColumn, 1, 1);
var dataRow = sheet.getRange((i+2), 1, 1, (lastColumn - 2));
function mergeTasks() {
function docCreator() {
var docTemplate1 = DriveApp.getFileById("");
var docTemplate2 = DriveApp.getFileById("");
var folderDestination = DriveApp.getFolderById("");
var clientName = sheet.getRange((i+2), 2, 1, 1).getValue();
var rawSubmitDate = sheet.getRange((i+2), 1, 1, 1).getValue();
var submitDate = Utilities.formatDate(rawSubmitDate, "PST", "MM/dd/yy");
var typeCheck = sheet.getRange((i+2), (checkColumn - 1), 1, 1).getValue();
if (typeCheck == "Type 1") {
var docToUse = docTemplate1;
var emailBody = HtmlService.createHtmlOutputFromFile("").getContent();
} else {
var docToUse = docTemplate2;
var emailBody = HtmlService.createHtmlOutputFromFile("").getContent();
}
var docName = "" + clientName + " - " + submitDate;
var docCopy = docToUse.makeCopy(docName, folderDestination);
var docId = docCopy.getId();
var docURL = DriveApp.getFileById(docId).getUrl();
var docToSend = DriveApp.getFileById(docId);
var docInUse = DocumentApp.openById(docId);
var docBody = docInUse.getBody();
var docText = docBody.getText();
function tagReplace() {
var DOBCell = sheet.getRange((i+2), 3, 1, 1);
var rawDOB = DOBCell.getValue();
if (rawDOB !== "") {
var DOB = Utilities.formatDate(rawDOB, "PST", "MM/dd/yy");
} else {
var DOB = ""
}
var taggedArray = docText.match(/\<{2}[\w\d\S]+\>{2}/g);
var headerArray = sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues();
var dataArray = dataRow.getValues();
dataArray[0][2] = DOB;
var strippedArray = [];
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
strippedArray.push(taggedArray[t].toString().slice(2, -2));
}
}
function dataMatch() {
for (var s = 0; s < strippedArray.length; s++) {
for (var h = 0; h < headerArray[0].length; h++) {
if (strippedArray[s] == headerArray[0][h]) {
docBody.replaceText(taggedArray[s], dataArray[0][h]);
}
}
}
docInUse.saveAndClose();
}
tagStrip();
dataMatch();
}
function emailCreator() {
var emailTag = sheet.getRange((i+2), (checkColumn - 9)).getValue();
var emailSubject = "" + clientName;
MailApp.sendEmail({
to: emailTag,
subject: emailSubject,
htmlBody: emailBody,
attachments: [docToSend.getAs(MimeType.PDF)],
replyTo: "",
});
}
tagReplace();
statusCell.setBackground(yellow);
emailCreator();
urlCell.setValue(docURL);
}
statusCell.setBackground(red);
docCreator();
statusCell.setBackground(green);
}
mergeTasks();
}
}
}
checkAndComplete();
}