r/GoogleAppsScript • u/pokeg0 • Jan 14 '18
Script to send email based on cell reference on Sheets
6
Upvotes
I am using the script below to send emails when a cell is changed to yes but for some reason when the cell is changed to yes the email is sent to all the email addresses in the sheet rather than just the email address on that row.
function EmailScrip() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 1");
// Sets "range" from A2 (2,1) to Bottom right cell of sheet (MaxRow,MaxColumn)
var range = sheet.getRange(2,1,sheet.getMaxRows()-1,sheet.getMaxColumns());
var data = range.getValues()
var activeRng,activeCell,columnToCheck,editedColumn,editedRow,newValue,sh,ss,valueToTestFor, email;//Define variables without assigning a value
//USER INPUT
columnToCheck = 10 ;//Column A is 1
valueToTestFor = "Y"
//END OF USER INPUT
ss = SpreadsheetApp.getActiveSpreadsheet();//Get the active spreadsheet
sh = ss.getActiveSheet();//Get the active sheet tab
activeRng = SpreadsheetApp.getActiveRange();//Get the active range
activeCell = activeRng.getCell(1, 1);//Get the first cell in the active range
newValue = activeCell.getValue();//Get the new value in the cell that was just edited
editedColumn = activeCell.getColumn();//Get the column of the cell that was just edited
editedRow = activeCell.getRow();//Get the row of the cell that was just edited
if (editedColumn !== columnToCheck) //Only run the code if the column to monitor is the correct one
return;
//Loops through data, 0 to the "length" of the data, set above (dictated by range), with i to be each row number with each loop, and row[X] representing Column X for row i.
for (var i = 0; i < data.length; ++i) {
// Setting all variables for email messages
// Column A = row[0], Column B = row[1],C2,D3,E4,F5,G6,H7,I8,J9,K10,L11,M12,N13,O14,P15,Q16,R17,S18,T19,U20,V21,W22,X23
var row = data[i];
var firstname = row[1];
var email = row[2];
var email2 = row [3];
var email3 = row [4];
var emailstatus = row[13]
var emailPattern = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
var validEmailAddress = emailPattern.test(email);
if (newValue === valueToTestFor && emailstatus != "Email_Sent") {
var message = "<HTML><BODY>"
+ "<P>Dear " + firstname + ","
+ "<br /><br />"
+" Your device has been repaired"
+ "<br /><br />"
+ "Regards"
+ "<br /><br />"
+ "Test"
+ "<br /><br />"
+ "</HTML></BODY>";
MailApp.sendEmail({
to:email,
cc:email2,
bbc:email3,
subject:"Device Repair",
htmlBody: message});
sheet.getRange(i+2,12).setValue("Email Sent");
}
}
} Also for the following code, I would like the message to be "firstname device has been repaired" rather than dear firstname.
var message = "<HTML><BODY>"
+ "<P>Dear " + firstname + ","
+ "<br /><br />"
+" Your device has been repaired"