Email notification when cell value is <=7 or >=7 - email

I need help trying to make this script work. I want to get daily email notifications if column Y3:Y is less than or equal to 7 OR Y3:Y is greater than or equal to 0. I want it to return information from column Q specific to that row.
So far, I have:
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = "x#email.com";
var message = '';
if(cell.indexOf('Y')<=7){
message = sheet.getRange('Q'+ sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'Order is due soon for'+sheet.getName();
var body = sheet.getName() + ' order is due soon. Click ' + ss.getUrl() + ' to see which PO is due, look at row # to see details: «' + row + '». PO#: «' + cellvalue;
MailApp.sendEmail(recipients, subject, body);
};
I have this for my trigger.
Here is the sheet: https://docs.google.com/spreadsheets/d/1HUaW1ZowU1ss1_JInLuML7jeVffDwZ5pl-EujooBJU4/edit?usp=sharing
I have a feeling my trigger is incorrect. Sorry in advance, still new to this.
Thanks!

I think this is closer to what you want
function sendNotification() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var row = sh.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = "x#email.com";
const vs = sh.getRange("A3:Y" + sh.getLastRow()).getValues();
const name = sh.getName();
const url = ss.getUrl();
let rows = [];
vs.forEach((r, i) => {
if (r[24] > -1 && r[24] < 8) {
rows.push(r);//save array of all rows
let message = r[16];
let row = i + 3;//added row number
let subject = 'Order is due soon for' + name;
var body = name + ' order is due soon. Click ' + url + ' to see which PO is due, look at row # to see details: «' + row + '». PO#: «' + cellvalue;
MailApp.sendEmail(recipients, subject, body);
}
})
Logger.log(JSON.stringify(rows));
}

Related

Script to send email based on value in a column - problem with script

New to GAS. I have a Google Form feeding into a spreadsheet. After watching tutorial videos and reading other posts, I attempted to create a script that will send an email to an address in column 2, and send a different email based on either a yes or no in another column (column 25). It also includes another column (26) that I want to have the date populated into when the email is sent, ensuring that every time I run this script, there are no duplicates sent. I have debugged and nothing comes up as an error, but it's not working - I have not received an email. Help would be greatly appreciated! Here is an example spreadsheet: https://docs.google.com/spreadsheets/d/1AKaSOk1ZbnfKeadgB_mugnqplKzJJ3bDQ_KsRY0sMvQ/edit?usp=sharing
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var responses = ss.getSheetByName("Field Trip Requests");
var data = responses.getRange(2,1,responses.getLastRow()-1,25).getValues();
data.forEach(function(row,i) {
// variables
var recipient = row[1];
var destination = row[6];
var approval = row[24];
var emailSent = row[25];
if(emailSent == ' ') {
if(approval == "Y") {
var body = "Your field trip request for " +
destination +
" has been approved! If you requested transportation, Najma will make arrangements and contact you if she requires more information." +
"<br><br>" +
"Cheers," +
"<br><br>" +
"Boaty McBoatface";
}
else if(approval == "N") {
var body = "Your field trip request for " +
destination +
" has not been approved. Please come and see me and we can chat!" +
"<br><br>" +
"Cheers," +
"<br><br>" +
"Boaty McBoatface";
}
var subject = "Your Field Trip Request";
MailApp.sendEmail(recipient, subject, body)
var d = new Date();
responses.getRange(i + 1, 25).setValue(d);
}
})
}
One problem of the script is that you it's using 1 based indexes when it should be using 0 based in
var recipient = row[1];
var destination = row[6];
var approval = row[24];
var emailSent = row[25];
The above is because JavaScript uses 0 based indexes for Array elements (as well as for other things), so intestead of the above use
var recipient = row[0];
var destination = row[5];
var approval = row[23];
var emailSent = row[24];
Another problem is the following condition:
emailSent == ' ' /* is emailSent equal to a blank space? */
it should be
emailSent == '' /* is emailSent equal to an empty string? */
the above because getValues() returns an empty string for empty cells
If this var data = responses.getRange(2,1,responses.getLastRow()-1,25).getValues(); is correct then there is no row[25] as shown below:
data.forEach(function(row,i) {
// variables
var recipient = row[1];
var destination = row[6];
var approval = row[24];
var emailSent = row[25];
row starts at zero and ends at 24
row is an array
Perhaps this is what you wish:
function sendEmail() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Field Trip Requests");
var data=sh.getRange(2,1,responses.getLastRow()-1,25).getValues();
data.forEach(function(row,i) {
var recipient=row[0];
var destination=row[5];
var approval=row[23];
var emailSent=row[24];
if(emailSent=='' && approval=='Y') {
var body=Utilities.formatString('Your field trip request for %s has been approved! If you requested transportation, Najma will make arrangements and contact you if she requires more information. <br><br>Cheers<br><br>Boaty McBoatface',destination);
}else if(emailSent=='' && approval == "N") {
var body=Utilities.formatString('Your field trip request for %shas not been approved. Please come and see me and we can chat!<br><br>Cheers,<br><br>Boaty McBoatface',destination);
}
var subject="Your Field Trip Request";
MailApp.sendEmail(recipient, subject, body);
sh.getRange(i+1,25).setValue(Utilities.formatDate(new Date, Session.getScriptTimeZone(), "MM/dd/yyyy"));
})
}

set values after sending mail

I want the script to send an email to those mail addresses where unchecked boxes are in the row - This works fine. But I want the value of the checkbox to be set “True” after the mails were sent.
My Problem is that I need the last for-loop to stop after all checkboxes are checked. In other words: The last loop has to stop when an empty cell appears.
First of all I manually trigger the script - later I will start it with the help of a button in the menu (function onOpen...)
Appreciate any help – thanks a lot!
Check out the sheet and the code below:
function sendmail() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var r = s.getRange('C:C'); //Checkboxes
var v = r.getValues();
for(var i=v.length-1;i>=0;i--)
if(v[0,i]=='false') {
var range = ss.getRange("A1:D4");
var UserData = range.getValues();
var UserData = range.getValues();
var row = UserData[i];
var name = row[0];
var email = row[1];
MailApp.sendEmail(row[1], "Test", "Hello " + name + ", This is an email");
var response = ui.alert("mail was send to ", ui.ButtonSet.OK);
}
for (k=1; k < 20; k++) { //loop which has to stop
s.getRange(k, 3).setValue("True");
}
}
A couple of major changes in your script.
The condition for the loop is wrong. Change to:
for(var i=v.length-1;i>0;i--)
The UI response is missing the recipient name. Change to:
var response = ui.alert("mail was send to "+name, ui.ButtonSet.OK);
var UserData = range.getValues(); is declared twice: delete one row
Immediately after the UI alert (and still within the IF loop), add a line to update the checkbox: UserData[i][2] = true;
Simplify the updating of checkboxes.
Delete the existing lines:
for (k=1; k < 20; k++) {
s.getRange(k, 3).setValue("True");
}
Substitute:
range.setValues(UserData)
Revised Script
function sosendmail() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var r = s.getRange('C:C'); //Checkboxes
var v = r.getValues();
for(var i=v.length-1;i>0;i--)
if(v[0,i]=='false') {
var range = ss.getRange("A1:D4");
var UserData = range.getValues();
var row = UserData[i];
var name = row[0];
var email = row[1];
// MailApp.sendEmail(row[1], "Test", "Hello " + name + ", This is an email");
Logger.log("mail sent")
var response = ui.alert("mail was send to "+name, ui.ButtonSet.OK);
UserData[i][2] = true;
}
range.setValues(UserData)
}
Alternative Script
The following script is offered as an alternative. It avoids multiple getRange()/getValue statements and uses a more conventional top-down loop.
function sosendmail01() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
// get the number of rows (Alast)
var Avals = ss.getRange("A2:A").getValues();
var AlastRow = Avals.filter(String).length;
// Logger.log("DEBUG: number of rows = "+AlastRow)
// get the data range
var r = s.getRange(2, 1, AlastRow, 3);// get all the data
// Logger.log("DEBUG: the data range = "+r.getA1Notation())
var v = r.getValues(); // get the data
// loop through the rows of data
for (var i = 0;i<AlastRow;i++){
if (v[i][2] != false) {
// the checkbox is ticked Don't sent an email
// Logger.log("DEBUG: i:"+i+", name = "+v[i][0]+" - the checkbox is ticked");
} else{
// the checkbox IS NOT ticked - send an email
//Logger.log("DEBUG: i:"+i+", name = "+v[i][0]+" checkbox = "+v[i][2]+" - the checkbox is NOT ticked");
var name = v[i][0];
var email = v[i][1];
//MailApp.sendEmail(email, "Test", "Hello " + name + ", This is an email");
Logger.log("DEBUG: mail sent to "+name+" at "+email)
var response = ui.alert("mail was send to "+name, ui.ButtonSet.OK);
v[i][2] = true;
}
}
r.setValues(v);
}

Sending an email with an html body from another email address via google sheets

I'm having a problem sending an html body message from a Google sheet from another email address that is an alias.
I can send it using the mailApp, but when I switch to the GmailApp I can't seem to get it to work.
The script I am using is below:
function sendNotification(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var emailAdd = "email#yourdomain.com";
if(event.range.getA1Notation().indexOf("G") > -1 && sheet.getRange("G" + row).getDisplayValue() > 999 && emailAdd.length > 1)
{
var rowVals = getActiveRowValues(sheet);
var aliases = GmailApp.getAliases();
Logger.log(aliases);
GmailApp.sendEmail(
"email#yourdomain.com",
"Allocation Request - " + rowVals.quantity + " cases on " + rowVals.date,
{htmlBody: "There has been a new allocation request from " + rowVals.name + " in the " + rowVals.team + " team.<br \> <br \> "
+ "<table border = \"1\" cellpadding=\"10\" cellspacing=\"0\"><tr><th>Issuing Depot</th><th>Delivery Date</th><th>Case Quantity</th></tr><tr><td>"+rowVals.depot+"</td><td>"+rowVals.date+"</td><td>"+rowVals.quantity+"</td></tr></table>"
+ "<br \>To view the full details of the request, use the link below.<br \> <br \>" +
"Allocation Requests"
+"<br \> <br \><i>This is an automated email. Please do not reply to it.<\i>"},
{from: aliases[0]}
);
}
}
function getActiveRowValues(sheet){
var cellRow = sheet.getActiveRange().getRow();
// get depot value
var depotCell = sheet.getRange("E" + cellRow);
var depot = depotCell.getDisplayValue();
// get date value
var dateCell = sheet.getRange("F" + cellRow);
var date = dateCell.getDisplayValue();
// get quantity value
var quantCell = sheet.getRange("G" + cellRow);
var quant = quantCell.getDisplayValue();
// return an object with your values
var nameCell = sheet.getRange("B" + cellRow);
var name = nameCell.getDisplayValue();
var teamCell = sheet.getRange("C" + cellRow);
var team = teamCell.getDisplayValue();
return {
depot: depot,
date: date,
quantity: quant,
name: name,
team: team
} }
I've managed to get the email to send from my alias, but it just sends and message containing [object], whereas not sending it from an alias works fine.
Could someone take a look and see what I'm doing wrong? I've not been able to find an answer on here yet. Thanks.
Create an object then add elements to the object:
var bodyHTML,o,sendTO,subject;//Declare variables without assigning a value
o = {};//Create an empty object
bodyHTML = "There has been a new allocation request from " + rowVals.name;
o.htmlBody = bodyHTML;//Add the HTML to the object with a property name of htmlBody
o.from = aliases[0]; //Add the from option to the object
sendTO = "email#yourdomain.com";
subject = "Allocation Request - " + rowVals.quantity + " cases on " + rowVals.date;
GmailApp.sendEmail(sendTO,subject,"",o);//Leave the third parameter as an empty string because the htmlBody advanced parameter is set in the object.

Sending Email populated by google sheets

Our Engineering Department has a request form on Google that our company uses to notify us of projects and other issues that need attending. The requests are assigned a project lead in our weekly meeting. I'm trying to write a script that will populate an email using data from the spreadsheet the form is driving to notify both the requester and the project lead so that they can contact each other directly instead of email everyone in the Engineering Group for updates. I tried splicing two different codes to achieve this as I was unable to find code I could easily adapt to fit our goal. I have listed the links below to the codes I used to write what I have.
https://developers.google.com/apps-script/articles/sending_emails
https://www.youtube.com/watch?v=_ToKh2JLQYs
The code tells me "Invalid email:" and highlights MailApp.sendEmail, even with real email addresses. Can anyone help? I haven't written any code since high school web design. We are considering using this form of notification in a few of our other departments as well. Assuming I get this version to work.
function SendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; //First row of data to process
var numRows = 2; //Number of rows to process
// Fetch the range of cells A2:L3
var dataRange = sheet.getRange(startRow, 1, numRows, 12)
// Fetch values for each row in the Range.
var Data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var requestername = row[1]; // Second column
var emailAddr = row[2]; // Third column
var requestspecifics = row[5]; // Sixth column
var projectlead = row[6]; // Seventh column
var projectleademail = ""; // Tenth Column
else if (projectlead == "Tom Smith") {projectleademail = "tom#fakeemail.com";}
else if (projectlead == "Dick Smith") {projectleademail = "dick#fakeemail.com";}
else if (projectlead == "Harry Smith") {projectleademail = "harry#fakeemail.com";}
else if (projectlead == "none") {projectleademail = null;}
var emailSent = row[12]; // Last column
if (emailSent !=EMAIL_SENT) { // Prevents sending duplicates
var myheader = "Minor Engineering Projects Requests";
MailApp.sendEmail({
to:emailAddr,
subject:myheader
body:requestername + ", \n\n + requestspecifics + " \n\nThe request you
submitted, listed above, has been assigned to " + projectlead + ". \nPlease
contact this person with any concerns. \n\nThank You, \n\nEngineering",
cc:projectlead]);
sheet.getRange(startRow + i,12).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
I don't know if the code above was an exact copy/paste of your actual script but if it was it has a lot of syntax errors that I (hopefully) corrected, please give it a try, it should work if the structure of your spreadsheet is right...
function SendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; //First row of data to process
var numRows = 2; //Number of rows to process
// Fetch the range of cells A2:L3
var dataRange = sheet.getRange(startRow, 1, numRows, 12)
// Fetch values for each row in the Range.
var Data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var requestername = row[1]; // Second column
var emailAddr = row[2]; // Third column
var requestspecifics = row[5]; // Sixth column
var projectlead = row[6]; // Seventh column
var projectleademail = ""; // Tenth Column
if (projectlead == "Tom Smith") {projectleademail = "tom#fakeemail.com";}
else if (projectlead == "Dick Smith") {projectleademail = "dick#fakeemail.com";}
else if (projectlead == "Harry Smith") {projectleademail = "harry#fakeemail.com";}
else if (projectlead == "none") {projectleademail = null;}
var emailSent = row[12]; // Last column
if (emailSent !="EMAIL_SENT") { // Prevents sending duplicates
var myheader = "Minor Engineering Projects Requests";
MailApp.sendEmail({
to:emailAddr,
subject:myheader,
body:requestername + ", \n\n" + requestspecifics + " \n\nThe request you"+
"submitted, listed above, has been assigned to " + projectlead +
". \nPlease contact this person with any concerns. \n\nThank You, \n\nEngineering",
cc:projectlead});
sheet.getRange(startRow + i,12).setValue("EMAIL_SENT");
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}

Problems with email notification

I'm new to using the google doc script editor so please be kind. Here's what I have so far:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get Active cell
var mycell = ss.getActiveSelection();
var cellcol = mycell.getColumn();
var cellrow = mycell.getRow();
//Define variables from sheet by column
//Column count starts at 0, not 1.
var timestamp = e.values[cellrow,14];
var yourName = e.values[cellrow, 0];
var email = e.values[cellrow, 1];
var plot2013 = e.values[cellrow, 5];
var plotrequest = e.values[cellrow, 6];
var sharing = e.values[cellrow, 7];
var totalprice = e.values[cellrow, 8];
var paid = e.values[cellrow, 13];
var subject = "TSF Payment Confirmation"
//email body
var emailBody = "Thank you for your payment submitted on " + timestamp +
"\n\nThe details you entered were as follows: " +
"\nYour name: " + yourName +
"\nYour plot #: " + plot2013 +
"\nNumber plots requested: " + plotrequest +
"\nSharing plot with: " + sharing +
"\nTotal payment: " + totalprice;
//html version of email body
var htmlBody = "Thank you for your payment submitted on <i>" + timestamp +
"</i><br/> <br/>The details you entered were as follows: " +
"<br/><font color=\"red\">Your Name:</font> " + yourName +
"<br/>Your Email: " + plot2013;
"<br/>Plots requested: " + plotrequest;
"<br/>Sharing plot with: " + sharing +
"<br/>Total payment: " + totalprice;
//sends email if cell contents are 'yes'
if (e.values[13,cellrow] == "yes") {
//Sends email
MailApp.sendEmail(email, subject, emailBody);
}
}
And what I'm hoping is that once a user clicks in column 13 (assuming its counting from 0 on the left, and not variable numbers) and types 'yes' it will email the information from that users row as specified.
I'm getting an error message, saying:
var timestamp undefined
I got that from this example here: http://alamoxie.com/blog/tech-tips/sending-confirmation-emails-google-docs-form/
You're trying to reference the cells in a way that doesn't make sense (or work). Try this tested/working code instead:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Ensure the event was triggered by typing "yes" in the appropriate column
if(e.range.getColumn() == 14 && e.value.toUpperCase() == "YES"){
// Get the corresponding row
var row = sheet.getRange(e.range.getRow(), 1, 1, sheet.getLastColumn()).getValues()[0];
// Define variable from row by column
var timestamp = row[14];
var yourName = row[0];
var email = row[1];
var plot2013 = row[5];
var plotrequest = row[6];
var sharing = row[7];
var totalprice = row[8];
var paid = row[13];
var subject = "TSF Payment Confirmation"
// Construct the email body
var emailBody = "Thank you for your payment submitted on " + timestamp +
"\n\nThe details you entered were as follows: " +
"\nYour name: " + yourName +
"\nYour plot #: " + plot2013 +
"\nNumber plots requested: " + plotrequest +
"\nSharing plot with: " + sharing +
"\nTotal payment: " + totalprice;
// Construct an HTML version of the email body
var htmlBody = "Thank you for your payment submitted on <i>" + timestamp +
"</i><br/> <br/>The details you entered were as follows: " +
"<br/><font color=\"red\">Your Name:</font> " + yourName +
"<br/>Your Email: " + plot2013;
"<br/>Plots requested: " + plotrequest;
"<br/>Sharing plot with: " + sharing +
"<br/>Total payment: " + totalprice;
// Send email
MailApp.sendEmail(email, subject, emailBody);
}
}
Notice I put everything in a conditional statement; there's no sense in trying to parse all that data if a cell in column N wasn't changed to "yes". Immediately after, I retrieve all the values from the edited row and fill all your variables with the result. The rest is pretty much the same as you wrote it.
Good luck!