Send email on matching cell value in a Sheet - google-apps-script

I am trying to send email when value of column 8 matched column 3 for all the rows in a google script .
function sendEmailNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lrow=ss.getLastRow()
var sheet = SpreadsheetApp.getActiveSheet();
for (var i = 2; i < lrow; i++)
{
if (sheet.getRange(i, 8).getValue() = sheet.getRange(i, 3).getValue())
var emailSubject = 'Value of ' + sheet.getRange(i, 1).getDisplayValue() + ' triggered, now pending your attention';
var emailBody = 'Person1 has approved the item on row ' + ' of spreadsheet "' + '".\n\n';
emailBody += 'To open the spreadsheet, click this link: ' + ss.getUrl() + '\n\n';
emailBody += '(this is an automatically sent message)';
MailApp.sendEmail("sdas22#gmail.com", emailSubject, emailBody);
; }}

The main problem is the IF statement
This is yours which does not work and which is generating an error message
if (sheet.getRange(i, 8).getValue() = sheet.getRange(i, 3).getValue())
This is mine which does work
if ((sheet.getRange(i, 8).getValue()) == (sheet.getRange(i, 3).getValue())){
}
A couple of things to note.
The comparison operator is "==" rather than "="
The each of the getValue statements are encapsulated in brackets
There are no "curly brackets" to indicate the purpose of the IF statement. This is particular important.
There's also semicolon on the last line that seem out of place.
This is my version of your code - which runs
function sendEmailNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lrow=ss.getLastRow()
var sheet = SpreadsheetApp.getActiveSheet();
for (var i = 2; i < lrow; i++)
{
if ((sheet.getRange(i, 8).getValue()) == (sheet.getRange(i, 3).getValue())){
var emailSubject = 'Value of ' + sheet.getRange(i, 1).getDisplayValue() + ' triggered, now pending your attention';
var emailBody = 'Person1 has approved the item on row ' + ' of spreadsheet "' + '".\n\n';
emailBody += 'To open the spreadsheet, click this link: ' + ss.getUrl() + '\n\n';
emailBody += '(this is an automatically sent message)';
MailApp.sendEmail("sdas22#gmail.com", emailSubject, emailBody);
}
}
}

Related

Auto Send Email When Checkbox is Checked - Google Sheet

I tried the script from Auto Email Function for Google Sheets Mobile and it worked the first time. When I tried to change the variables, it does not automatically send the email, unless I run the script again, it would then update the response sheet and then clears the checkbox. Please help me with this. Kindly see my code below.
function EmailNotification(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Course_AutoEmail'); //source sheet
var columnb = sheet.getRange('I:I'); //Column with check boxes
var columnbvalue = columnb.getValues();
var notifysheet = ss.getSheetByName('Responses'); //destination sheet
var data = [];
var rownum = [];
//Condition check in B:B (or check box column); If true copy the same row to data array
for (let i = 0; i < columnbvalue.length; i++) {
if (columnbvalue[i][0] === true) {
var columnb2 = sheet.getRange('I747:I'); //row started in row 747
columnb2.setValue('false');
data.push.apply(data, sheet.getRange(i + 1, 1, 1, 20).getValues());
//Copy matched ROW numbers to rownum
rownum.push(i);
//Copy data array to destination sheet
notifysheet.getRange(notifysheet.getLastRow() + 1, 1, data.length, data[0].length).setValues(data);
var activeRow = notifysheet.getLastRow();
var name = notifysheet.getRange(activeRow, 1).getDisplayValue(); // The number is the column number in the destination "responses" sheet that you want to include in the email
var employeeID = notifysheet.getRange(activeRow, 2).getDisplayValue();
var position = notifysheet.getRange(activeRow, 3).getDisplayValue();
var team = notifysheet.getRange(activeRow, 4).getDisplayValue();
var date = notifysheet.getRange(activeRow, 10).getDisplayValue();
var rec1 = notifysheet.getRange(activeRow, 19).getDisplayValue();
var rec2 = notifysheet.getRange(activeRow, 20).getDisplayValue();
var email = rec1 + "," + rec2;
var subject = name + ': 201 Completion';
//Body of the email message, using HTML and the variables from above
var message =
'<br><div style="margin-left:10px;">Hi, </div>' +
'<br><div style="margin-left:10px;">Good day!</div>' +
'<br><div style="margin-left:10px;"><b>' + name + '</b> has completed the course. </div>' +
'<br><div style="margin-left:20px;"><h3 style="text-decoration: underline; color: #f36f21">Employee Details: </h3></div>' +
'<div style="margin-left:25px;">Name: <b>' +
name +
'</b></div>' +
'<div style="margin-left:25px;">Position: <b>' +
position +
'</b></div>' +
'<div style="margin-left:25px;">Team: <b>' +
team +
'</b></div>' +
'<div style="margin-left:25px;">Completion Date: <b>' +
date +
'</b></div>' +
'<br><br><div style="margin-left:10px;">Let me know if you have any questions. </div>' +
'<br><div style="margin-left:10px;">Thanks! </div>';
MailApp.sendEmail(email, subject, '', {
htmlBody: message,
name: 'Updates',
});
}
}
}
I read your code.
if you don't want your checked checkbox unchecked in spreadsheet.
so you have to remove `columnb2.setValue('false');` line of code.
this line is made checkbox unchecked.
solution of other problems : http://one7techlab.com

sendEmail() schedule trigger sends an empty email, but running from the script editor sends accurate data?

When I inserted query function into the sheet from which it pulls the data, I began to get blank emails when the trigger ran. When I go into the script editor and debug or run, I get the email the way it is programmed to run
Email I receive on scheduled send:
Email I receive when sent from Script Editor
Here is the code I am running:
function sendEmail() {
//setup function
var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var StartRow = 2;
var aVals = ActiveSheet.getRange("A1:A").getValues();
var aLast = aVals.filter(String).length;
var RowRange = aLast - StartRow + 2;
var WholeRange = ActiveSheet.getRange(StartRow, 1, RowRange, 10);
var AllValues = WholeRange.getValues();
var message = "";
//iterate loop
for (i in AllValues) {
//set current row
var CurrentRow = AllValues[i];
//define column to check if sent (starts from "0" not "1")
var hasTracking = CurrentRow[8];
//if row has been sent, then continue to next iteration
if (hasTracking !== "")
continue;
//set HTML template for information
message +=
"<p><b>Order: </b>" + CurrentRow[0] + "</p>" +
"<p><b>Name: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Date Initiated: </b>" + CurrentRow[5] + "</p>" +
// "<p><b>Date Initiated: </b>" + Utilities.formatDate(CurrentRow[5], "GMT", "MM-dd-YYYY") + "</p>" +
"<p><b>Gorgias Link: </b>" + CurrentRow[6] + "</p><br><br>";
//set the row to look at
var setRow = parseInt(i) + StartRow;
//mark row as "sent"
//ActiveSheet.getRange(setRow, 11).setValue("sent");
}
//define who to send grants to
var SendTo = "XXX#XXX.com";
//set subject line
var Subject = "Returns Needing Processed";
//send the actual email
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: Subject,
htmlBody: message,
});
}
Don't use .getActiveSheet() when you run the function via a trigger.
The reason is that .getActiveSheet() gets the active sheet of your file which can be any sheet.
Instead use .getSheetByName().
Replace:
var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
with:
var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
adjust Sheet1 with your specific case.

Get value from formula cell to trigger email sending

I am trying to get an e-mail to be sent when the value in a cell that contains a formula goes below a certain number.
I have achieved this for various other spreadsheets that have the cell value manually entered, but for this specific one sheet where the value on the cell results from a simple SUM formula, the e-mail is not being sent. Now if I enter the value manually into the cell, the e-mail is sent right away.
Below is the code and here is a copy of my spreadsheet:
https://docs.google.com/spreadsheets/d/1gnmJfkmIKHyNqLqTFK-bdOZnh2Ejkia6xo3r_3cjwkk/edit?usp=sharing
function CheckBasketsInventory(e) {
var ss = e.source;
var inventorySheet = ss.getSheetByName("Baskets");
var rowIndex = e.range.getRow();
var columnIndex = e.range.getColumn();
var numCols = 11;
var row = inventorySheet.getRange(rowIndex, 1, 1, numCols).getValues()[0];
var editedInventory = row[10];
var editedMinimum = row[8];
var sheetName = ss.getActiveSheet().getName();
// Checking that: (1) edited cell is an inventory quantity, and (2) Inventory is below minimum
if(editedInventory <= editedMinimum && sheetName == "Baskets" && columnIndex == 11 && rowIndex > 1) {
var inventoryValues = inventorySheet.getDataRange().getValues();
var emailBody = "";
for(var i = 1; i < inventoryValues.length; i++) {
var inventory = inventoryValues[i][10];
var minimum = inventoryValues[i][8];
if(inventory <= minimum) {
var productName = inventoryValues[i][0] + " " + inventoryValues[i][1] + " " + inventoryValues[i][2];
var productUnits = minimum + " " + inventoryValues[i][9];
var messagePart1 = "Inventory for " + productName + " has gone under " + productUnits + ". ";
var messagePart2 = "Organise purchase order. Inventory as of today is: " + inventory + " " + inventoryValues[i][9];
var message = messagePart1.concat(messagePart2);
var newItem = "<p>".concat(message, "</p>");
emailBody += newItem;
}
}
var emailSubject = "Low inventory alert";
var emailAddress = "danielrzg#gmail.com";
// Send Alert Email
if(emailBody != "") {
MailApp.sendEmail({
to: emailAddress,
subject: emailSubject,
htmlBody: emailBody
});
}
}
}
Thank you.
As you can see in the documentation:
Script executions and API requests do not cause triggers to run. For
example, calling FormResponse.submit() to submit a new form response
does not cause the form's submit trigger to run.
This includes values edited by a Sheet Formula not triggering an onEdit trigger.

Trouble automating email from google sheets

I am very new to google script and cannot work out why my script is not functioning. When I try to run the code I get the following error code -
TypeError: Cannot read property "range" from undefined. (line 2, file "Code"
If anybody could give a novice some help that would be greatly appreciated!
function sendEmail(event){
var sheet = event.range.getSheet();
if(sheet.getName() !== 'Sheet1') {
// if it's not the correct sheet we end the function here
return;
}
var range = event.range;
var row = range.getRow(); // we get the index of the row of the
edited
cell
var dataRange = sheet.getRange("A" + row + ":C" + row);
var values = dataRange.getValues();
var rowValues = values[0];
var recipient = rowValues[0];
var email = rowValues[1];
var refillsNumber = rowValues[2];
if (refillsNumber = 2) {
// if 'refillsNumber' is not equal to 2 we end the function here
var message = 'Dear ' + recipient + ',\n\n'+ 'You have ' +
refillsNumber + ' remaining would you like to buy more?' + '\n\n' +
'Kind regards,' + '\n\n' + 'The revol team.';
var subject = 'Refill reminder';
MailApp.sendEmail(email,subject,message);
return
}
if (refillsNumber !== 0) {
return}
var message = 'Dear ' + recipient + ',\n\n'+ 'You have ' +
refillsNumber + ' remaining would you like to buy more? If not then
would you like to end your subsription?' + '\n\n' + 'Kind regards,'
+ '\n\n' + 'The revol team.';
var subject = 'Refill reminder';
MailApp.sendEmail(email,subject,message);
return
}
// in addition to this script which aims to send an email to the
customer when they only have 2 refill remaining -
/// I also want to set up a function that sends an email when they
have 0 refills remaining
Send Emails by Editing Column C
I changed the Sheet name and added an extra condition. I also commented out the MailApp.sends and replaced them with writes to the sidebar so that I could test it without trying to send emails.
You will need to create an onEdit trigger for this function.
function sendMailOnEdit(event){
var sheet = event.range.getSheet();
if(sheet.getName() !== 'Sheet2' || event.range.columnStart!=3) {return;}
var range=event.range;
var row=range.rowStart;
var dataRange = sheet.getRange(row,1,1,3);
var values=dataRange.getValues();
var rowValues=values[0];
var recipient = rowValues[0];
var email = rowValues[1];
var refillsNumber = rowValues[2];
if (refillsNumber==2) {
var message = 'Dear ' + recipient + ',\n\n'+ 'You have ' + refillsNumber + ' remaining would you like to buy more?' + '\n\n' + 'Kind regards,' + '\n\n' + 'The revol team.';
var subject = 'Refill reminder';
//MailApp.sendEmail(email,subject,message);
var html=Utilities.formatString('<br />Email: %s<br />Subject: %s<br />message: %s<br /><hr>', email,subject,message);
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showSidebar(userInterface);
return
}
if (refillsNumber !== 0) {return}
var message = 'Dear ' + recipient + ',\n\n'+ 'You have ' + refillsNumber + ' remaining would you like to buy more? If not then would you like to end your subsription?' + '\n\n' + 'Kind regards,' + '\n\n' + 'The revol team.';
var subject = 'Refill reminder';
//MailApp.sendEmail(email,subject,message);
var html=Utilities.formatString('<br />Email: %s<br />Subject: %s<br />message: %s<br /><hr>', email,subject,message);
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showSidebar(userInterface);
}
This is what my spreadsheet looks like:
And let me remind you that you cannot run this function without an event object.

Can you Sendnotification in Google Script for multiple sheets?

I'd like to send a notification to someone when a particular cell (ie document) is updated. Specifically, when a cell in one row is updated, it would send a notification to the owner listed in the same row. For example B47 gets updated, it send an email to B3.
I've gotten the script to work when it's pointed to one sheet. But when I try to ask the script to run over multiple sheets/tabs, I get error 'Script function not found: sendNotification' Is it possible to have this script work for multiple sheets/tabs in the same google doc? Updates are pulling from a different source so I'd like to keep using getSheetbyName instead of getActiveSheet.
Any help would be much appreciated. Here's my code where it stands:
function shellFunction() {
var sheets = ['Arabic', 'Portuguese'];
for (var s in sheets) {
toTrigger(sheets[s]);
}
function toTrigger(sheetName) {
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheets[s]);
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = sheet.getRange('J' + sheet.getActiveCell().getRowIndex()).getValue();
var message = '';
if (cell.indexOf('B') != -1) {
message = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'The ' + sheet.getRange('F' + sheet.getActiveCell().getRowIndex()).getValue() + ' ' + sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' needs your Translation';
var body = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' has been updated. Can you please update ' + sheet.getRange('G' + sheet.getActiveCell().getRowIndex()).getValue() + '? Please remember to update the date column in the Resource Document when the translation is complete:' + ss.getUrl();
MailApp.sendEmail(recipients, subject, body);
}
}
}
Should this line
var sheet = ss.getSheetByName(sheets[s]);
be changed to
var sheet = ss.getSheetByName(sheetName);
since that is the name of the passed sheet?
EDIT
There were a couple other items which may have caused issue. I made edits for this result:
function shellFunction() {
var sheets = ['Arabic', 'Portuguese'];
for (var s in sheets) {
toTrigger(sheets[s]);
}
}
function toTrigger(sheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = sheet.getRange('J' + sheet.getActiveCell().getRowIndex()).getValue();
var message = '';
if (cell.indexOf('B') != -1) {
message = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'The ' + sheet.getRange('F' + sheet.getActiveCell().getRowIndex()).getValue() + ' ' + sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' needs your Translation';
var body = sheet.getRange('A' + sheet.getActiveCell().getRowIndex()).getValue() + ' has been updated. Can you please update ' + sheet.getRange('G' + sheet.getActiveCell().getRowIndex()).getValue() + '? Please remember to update the date column in the Resource Document when the translation is complete:' + ss.getUrl();
MailApp.sendEmail(recipients, subject, body);
}
My first change was to not nest the functions. To do this I added a closing curly bracket before the toTrigger function and removed one of the last in your code. After that there was another nested function which actually made up all of the toTrigger function. It was called sendNotifocation which matched your error. I removed that by removing the line after the toTrigger function declaration and another curly bracket at the end of your code.
Last, I made the above edit. In my test it seemed to work fine, except that I commented out the call to actually send an email and only debugged to the line just prior to that point.