I currently have this script working so that when the last row is edited it sends an email with the contents of the first two columns from that row. My issue is that if info is entered into any column of the last row then a blank email gets sent. I've tried a combination of if statements to get the result I want but either end up with the script working as it currently is, or not working at all.
// This function grabs the last row of a inventory sheet and sends the updated range to a specified recipient using a onEdit trigger
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// If edit is not made on "Iventory" sheet then function does not proceed
if (sheet.getSheetName() != "Inventory") return;
// Get last row of sheet
var lastRow = sheet.getLastRow();
// Get range of last row
var lastCell = sheet.getRange(lastRow, 1, 1, 2);
// Fetch values for each row in the Range.
var data = lastCell.getValues();
//empty string
var message =""
//Loop through each row and form CSV data
for (var i = 0; i < data.length; i++) {
var row = data[i];
message = message + row[0] + "-" +row[1] + "\n";
}
// Send one email with all the rows
var subject = "Inventory update";
MailApp.sendEmail("test#test.com", subject, message);
}
try this:
var send=true;
for (var i=0;i<data.length;i++) {
var row = data[i];
message = message + row[0] + "-" +row[1] + "\n";
if(!row[0] || !row[1]){
send=false;
break;
}
}
// Send one email with all the rows
var subject = "Inventory update";
if(send){
MailApp.sendEmail("test#test.com", subject, message);
}
Related
Newbie looking for some help... I can't understand what is going wrong in this script!
I am using a sheet similar to this one. My objective is to send and email to a specific address whenever certain conditions are met.
The conditions are Col R (Yesterday = 1) & Col D (Status) is different than "Resgate".
This is the output I am getting from my script. If 2 rows meet these conditions, then I get an email with the first row that meets conditions, and then another email with the first and second row that meets conditions. If there where 5 rows that meet conditions, I would receive 5 emails, and in the last one, I would have all the rows that meet conditions.
What I want to achieve is to receive only the final email with all the rows that meet conditions and avoid receiving the other ones.
Email 1
Email 2
This Is the code I am using
function SENDMAIL() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// set active sheet to Sheet by name
spreadsheet.setActiveSheet(spreadsheet.getSheetByName("Sheet 1"));
var sheet = spreadsheet.getActiveSheet();
// figure out what the last row is
var lastRow = sheet.getLastRow();
var startRow = 2;
// grab all data from user to days left
var range = sheet.getRange(startRow, 1, lastRow - startRow + 1, 19);
var values = range.getValues();
var users1 = [];
var users2 = [];
var users3 = [];
var users4 = [];
var users5 = [];
var users6 = [];
// loop all data per row
values.forEach(function(row) {
if (row[17] == 1 && row[3] !== "Resgate") {
// add user if 4 or more days left
users1.push(row[3]);
users2.push(row[4]);
users3.push(row[5]);
users4.push(row[16]);
users5.push(row[15]);
users6.push(row[14]);
// if users has elements
var message = "<html><body></h1><p><b>New Requests</font2></h1>";
var names = "<ul>";
users4.forEach(function(user, i) {
names += `<p><b><li>${user} -> ${users1[i]} - ${users3[i]} - ${users2[i]} - ${users5[i]} - ${users6[i]}€ `;
});
names += "</ol>"
message = message + names + "</body></html>";
var flexmails = "Example#gmail.com";
MailApp.sendEmail(flexmails, "NEW PPR's", "", {
htmlBody: message,
noReply: true
});
} else {}
})
}
Simply move sendEmail out from the values.forEach loop and put it at the end of the script
MailApp.sendEmail(flexmails, "NEW PPR's","", { htmlBody: message, noReply: true });
values.forEach(function(row) {
if (row[17] == 1 && row[3] !== "Resgate") {
// add user if 4 or more days left
users1.push(row[3]);
users2.push(row[4]);
users3.push(row[5]);
users4.push(row[16]);
users5.push(row[15]);
users6.push(row[14]);
}
});
// if users has elements
var message = "<html><body></h1><p><b>New Requests</font2></h1>";
var names = "<ul>";
users4.forEach(function(user, i) {
names += `<p><b><li>${user} -> ${users1[i]} - ${users3[i]} - ${users2[i]} - ${users5[i]} - ${users6[i]}€ `;
});
names += "</ol>"
message = message + names + "</body></html>";
var flexmails = "Example#gmail.com";
MailApp.sendEmail(flexmails, "NEW PPR's", "", {
htmlBody: message,
noReply: true
});
I have been trying to retrofit an old code I have used to send emails before to send an email when the formula solution in a cell equals today's date in another cell.
Here is my code:
function sendtest(e) {
var ss = e.source;
var s = ss.getSheetByName("Test");
var r = e.range;
// Below is the line that selects what column to use for the send date
var actionCol = 2;
var colIndex = r.getColumnIndex();
// Testing if statement
if (e.value == s.getRange(2, 3).getValue () && colIndex == actionCol) {
// All rows below are used to send the email
var row = r.getRowIndex();
// This takes the email addresses in column D
var userEmail = s.getRange(row, 4).getValue ();
//The subject line of the email
var subject = "Test test " + s.getRange(row, 1).getValue ();
//The structure of the body of the email
var body = "It has been two weeks since test test, " + s.getRange(row, 1).getValue ();
body +="\n\ntest test?";
body +="\n\ntest test,";
body +="\n\ntest test";
// This line sends the email
MailApp.sendEmail(userEmail,subject,body);
}
}
EDIT: Sorry I forgot to state what is going wrong. Every time I attempt to trigger this script (time based), I get an error telling me that line 3 (get sheet by name) is undefined.
I have a spreadsheet for recording customer samples. A column [I] is used to calculate when the original entry date is over a certain period which then displays an overdue message using an if statement. I want to trigger a script to check this column daily and if 'overdue' is found to send an email to an address contained in another column [C]. I am also using another column [J] to return a message when an email has been sent. I am using the script below but am returning errors
The script marks all rows in column J with the sent email message
I appear to be collecting a bigger array of data have needed [adding two rows the the bottom]
Anyone any ideas?
//Setup the function
function autoMail () {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //Get the active spreadsheet
var sheet = ss.getSheetByName( 'TS_Requests' ); //Get the active spread
var startRow = 3; // Start of row that going to be process considering row 2 is header
var lastRow = sheet.getLastRow(); // Get the last row of data to be process
var lastColumn = sheet.getLastColumn(); // Get the last column of data to be process
var range = sheet.getRange(startRow,1,lastRow,lastColumn); //Getting the specific cell to be process
var data = range.getValues(); // Get the values inside the cell
for(var i=0;i<data.length;++i){
var row = data[i];
var email = row[2]; // Grab the email column. C in this case
var customer = row[3]; // Grab data for Email body
var item = row[5]; // Grab data for Email body
var description = row[6]; // Grab data for Email body
var status = row[8]; // Grab the column containing the value needed to be checked.
var EmailSent = row[9]
if (EmailSent != 'Email_Sent') { //Prevents e-mail being sent in duplicate
if(valstatus ='Overdue'){ // Check the values, if it's what's needed, do something
MailApp.sendEmail(email, 'Your sample request is overdue', customer + ' - ' + item + ' - ' + description); // if condition is met, send email
sheet.getRange(startRow + i, 10).setValue('Email_Sent');
}
}
}
}
I am relatively new to programming, and have recently been working on a script to send emails from a google spreadsheet when a cell in a certain column is changed. The recipient is assigned based off of an email address in another column in the same row as the change. I am having difficulty getting my code to stop running after the first email. As it is, the script runs indefinitely (at least until I run out of emails for the day).
Here is the code:
function sendNotification() {
var sheet = SpreadsheetApp.getActiveSheet();
//Get Active cell
var mycell = sheet.getActiveSelection();
var cellcol = mycell.getColumn();
var cellrow = mycell.getRow();
var address = sheet.getRange("C" + cellrow).getValue();
var streetAddress = sheet.getRange("F" + cellrow).getValue();
var startRow = 2;
var numRows = 2000;
// Fetch the range of cells A2:O2000
var dataRange = sheet.getRange(startRow, 1, numRows, 15)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = address; // First column
var message = streetAddress +" Has been Submitted for permitting!"; // Second column
var subject = "The above Address has been Submitted For Permitting! We will Follow up with you when it has been approved.";
//Check to see if column is H to trigger
if (cellcol == 8 && sheet.getName() == "Sheet1" && mycell !== "")
{
//Send the Email
MailApp.sendEmail(emailAddress, message, subject);
}
//End sendNotification
}
}
What can I do to resolve this? Would a loop be the best option? How would I implement this?
How about this approach?
var EMAIL_SENT = "EMAIL_SENT";
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var mycell = e.range;
var cellcol = mycell.getColumn();
var cellrow = mycell.getRow();
var emailAddress = sheet.getRange("C" + cellrow).getValue();
var streetAddress = sheet.getRange("F" + cellrow).getValue();
var subject = "The above Address has been Submitted For Permitting! We will follow up with you when it has been approved."
// Fetch values for each row in the Range
var message = streetAddress +" Has been Submitted for permitting!";
var emailSent = sheet.getRange("O" + cellrow).getValue();
if ( cellcol == 8 && sheet.getName() == "Sheet1" && emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(cellrow, 15).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
If you use the onEdit() the function will be triggered every time you edit the cell. Is this what you want?
What I assume you're looking for is a script that:
Reads every row of the active sheet
If the 8th column is not empty, sends an e-mail to the address in the first column
The whole script is trigger upon the user requests (not when the user edits a cell)
In this case the first approach is better, the sendNotification(). Also a loop is necessary to read all the rows. And the IF statement should be something like if (row[8] != "") then send the e-mail.
In this case row which was defined as row = data[i] in your first script will have the values of all the cells in the row being read in the loop. So row[8] will have the value of the 8th (column H), which you want to check for emptiness, thus if(row[8] != "").
Also, if I understand correctly the e-mail adress should be emailAddress = row[1] inside the loop, because the email address is different every row.
Your second approach var EMAIL_SENT = "EMAIL_SENT"; is almost similar to the simple extension of the code that sets the cells in a column to 'EMAIL_SENT' for each row after sendEmail is called given in Section 2: Improvements. Within tutorial, each cell was marked in each row every time an email is sent. With that, you should mark edited cells as unsent then you will be able to re-run the script later on, avoid sending email duplicates and will only send the edited cells.
To make your code more efficient and help you improve the performance of your scripts, there are also list of best practices given.
I have an action item Google sheet with these columns:
A - ID - a serial # 1, 2, 3, etc.
B - Assigned - date the action item was assigned
C - Product - short text name of the project or area
D - Action Item - text description of the action item
E - Owner - who is the item assigned to, this is usually just a name
like Bob L, or sometimes multiple people Bob/Ted
F - Due Date
G - Status - Pending, In process, etc.
H - Last Updated - updated by onEdit script
I - Last Edited By - updated by onEdit script
J - Owner Email - vlookup to data range to get email address(s) of
owner(s)
K - Last Reminder Sent - date of the last email sent updated by
script
I'm a total newbie with GAS so I've cobbled together snippets to get the script to send 1 email to the owner for each action item but I want to group the action items by column E (Owner) and send one email. I know I need a nested loop but I'm not sure how to proceed.
The format of the resulting email would need to be a table of columns A, B, D, F, G (at least). The current script is below:
SCRIPT
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 3; // First row of data to process
//var numRows = 12; // Number of rows to process *CHANGE AS NEEDED*
//var numItems = getRowsData(sheet, OpenItems);
var numItems = SpreadsheetApp.getActiveSheet().getRange("OpenItems").getValues();
var numRows = numItems[0]
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 11) // must encompass Column K (11)
// 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 actionitemid = row[0];
var assignedon = Utilities.formatDate(new Date(row[1]), "GMT-05:00", "MM/dd/yy");
var assignedto = row[4];
var project = row[2];
var actionitem = row[3];
var duedate = Utilities.formatDate(new Date(row[5]), "GMT-05:00", "MM/dd/yy");
if (duedate == "12/31/69") { // no due date
var duedate = "TBD - please update!!" ;}
var status = row[6];
var emailAddress = row[9]; // Column J = 9 (starts at A=0
var subject = "Action Item Reminder - Project: " + project;
var sheetURL = SpreadsheetApp.getActiveSpreadsheet().getUrl();
var body = "A reminder to do the following:\n\n Project: "+project + "\n Due: "+duedate+"\nAssigned: "+assignedon+"\n Owner: "+assignedto+"\n Status: " + status + "\n\nACTION ITEM: "+actionitemid+"\n=============================\n"+actionitem+"\n=============================\n\nPlease advise if you will not meet the due date ASAP.\n\nAll action items can be found in the Action Item sheet:\n"+sheetURL+".";
var emailSent = row[11]; // Column D = 3
// if (oktosend == "Y") { // Send only for marked rows
var ok = emailAddress.length
if ( emailAddress.length > 0) {
// Send email
// MailApp.sendEmail(emailAddress, subject, body);
// MailApp.sendEmail(emailAddress, "TEST", body);
MailApp.sendEmail({
to: emailAddress,
cc: "rdeloach#rentpath.com",
subject: subject,
body: body
});
// Update EmailSent
var time = new Date();
time = Utilities.formatDate(time, "GMT-05:00", "MM/dd/yy, hh:mm");
sheet.getRange(startRow + i, 11).setValue(time); // Use column for EmailSent + 1 here getRange(startRow + i, X)
// Update oktosend to N
// sheet.getRange(startRow + i, 5).setValue('N'); // Use column for oktosend + 1 here getRange(startRow + i, X)
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
} //oktosend<>N
}
}
OUTPUT/RESULT
Subject: Action Item Reminder - Project: Project X
A reminder to do the following:
Project: Project X
Due: 3/1/14
Assigned: 02/01/14
Owner: Rick D
Status: Pending
ACTION ITEM: 1
~~~~~~~~~~~~~~~~~~~~~~~
Provide the data requirements for the new database tables on project X.
~~~~~~~~~~~~~~~~~~~~~~~
Please advise if you will not meet the due date ASAP.
All action items can be found in the Action Item sheet:
END OUTPUT
Looking for help on the grouping and producing a table in Gmail.
You can put the table in the body of the message and then send it through the GmailApp service instead of MailApp.
var body = '<table><tr><td>col</td><td>val</td></tr></table>';
GmailApp.sendMail('to#example.com', 'subject', '',
{ cc: 'cc#example.com',
htmlBody: body
});