Automatic Email from Google Sheets with email from row - email

I am trying to apply this code to a google sheet which I use to track name change requests. The customer submits a form and when they don't submit all the required information I select rejected from the dropdown on the spreadsheet. I have the form collect the username when the customer submits the form. I was wondering if it is possible to modify the code below to grab the email address from the row of the active cell that the status was changed and email the customer to inform them their request is rejected.
function sendEmail(email_address, email_subject, email_message) {
var status = ScriptProperties.getProperty('Order Status') + "";
var value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FCNC Responses").getActiveCell().getValue().toString();
if (value.match("Rejected" ) && status.match("")) {
ScriptProperties.setProperty('Order Status', '')
MailApp.sendEmail('username#nps.gov', 'Rejected Fleet Card Name Change', '. Fleer User, Please review the Fleet Card Name Change page for Status Updates.": ');
}
else {
if (!value.match("Rejected" ))
ScriptProperties.setProperty('Order Status', '')
}
}

You can use a function with dataRange.getValues().
getValues()
Returns the rectangular grid of values for this range. Returns a two-dimensional array of values, indexed by row, then by column. The values may be of type Number, Boolean, Date, or String, depending on the value of the cell. Empty cells will be represented by an empty string in the array. Remember that while a range index starts at 1, 1, the JavaScript array will be indexed from [0][0].
Here is a code sample from a related SO question:
function findCell() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
for (var i = 0; i < values.length; i++) {
var row = "";
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == "User") {
row = values[i][j+1];
Logger.log(row);
Logger.log(i); // This is your row number
}
}
}
}
From there you can add the code that will send email if the value of the specific cell is rejected.
Happy coding, hope it helps!

Related

Send single email containing a table based on a condition to the recipients when the names are repetitive using google app script

This is the extended version of my previous question.
I want to send email once in a week to the recipients based on the status column.
Sheet Link: https://docs.google.com/spreadsheets/d/1GC59976VwB2qC-LEO2sH3o2xJaMeXfXLKdfOjRAQoiI/edit#gid=1546237372
The previous code is attached in the sheet.
From the sheet, When the Status column will be new and ongoing, a table will be generated with column Title, Link and due date and send a single email to the recipients even they are repeated.
In the sheet, For resource Anushka, Status New appeared twice and Ongoing once. The table will be like-
Anushka || New || 10/25/2022
Anushka || New || 10/25/2022
Anushka || Ongoing || 10/25/2022
And after creating it, it will send single email to each recipients though they have appeared several times.
I have done it for getting multiple emails whatever the status is with the help of another commenter from stackflow but I want to modify it and change it. The code for this one is a bit longer as I have two helper gs file, html table code and the main one. That's why I am not writing all the codes here. But in the sheet from the extension, one can see my code.
If anyone give me suggestions how to change or modify the logic, it will be appreciated.
Code
function macro(){
// get range of cell with data from A1 to any cell near having value (call data region)
var table = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getRange("A1").getDataRegion();
var header=table.getValues()
var resource=header[0][1]
var status_r=header[0][3]
var due_date_r=header[0][5]
var link_r=header[0][10]
// create custom table filtered by the column having header "State" where the value match "New"
var filterTable = new TableWithHeaderHelper(table)
.getTableWhereColumn("Status").matchValueRegex(/(New)/);
// for each row matching the criteria
for(var i=0; i< filterTable.length() ; i++){
// Get cell range value at column Mail
var mail = filterTable.getWithinColumn("Email").cellAtRow(i).getValue();
// Any other value of column Target Value
var resource_col = filterTable.getWithinColumn("Resource").cellAtRow(i).getValue();
var status_col = filterTable.getWithinColumn("Status").cellAtRow(i).getValue();
var due_date_col = filterTable.getWithinColumn("Due Date").cellAtRow(i).getValue();
var link_col = filterTable.getWithinColumn("Link").cellAtRow(i).getValue();
var new_data=[[resource_col,status_col,due_date_col,link_col]]
var htmltemplate=HtmlService.createTemplateFromFile("email")
htmltemplate.resource=resource
htmltemplate.status_r=status_r
htmltemplate.due_date_r=due_date_r
htmltemplate.link_r=link_r
htmltemplate.new_data=new_data
var htmlformail=htmltemplate.evaluate().getContent()
var subjectMail = "Automation Support Services Actions Items";
var dt1 = new Date()
var dt2 = due_date_col
// get milliseconds
var t1 = dt1.getTime()
var t2 = dt2.getTime()
var diffInDays = Math.floor((t1-t2)/(24*3600*1000));
// 24*3600*1000 is milliseconds in a day
console.log(diffInDays);
// Send email
MailApp.sendEmail({
to:mail ,
subject: subjectMail,
htmlBody:htmlformail,
});
}
}```
2 loops can make the job.
// get range of cell with data from A1 to any cell near having value (call data region)
var table = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getRange("A1").getDataRegion();
// init html header data
var header=table.getValues()
var resource=header[0][1]
var status_r=header[0][3]
var due_date_r=header[0][5]
var link_r=header[0][10]
var listOfEmails = [];
var tableWithHeader = new TableWithHeaderHelper(table)
// get all email
for(var i=0; i< tableWithHeader.length() ; i++){
var mail = tableWithHeader.getWithinColumn("Email").cellAtRow(i).getValue();
listOfEmails.push(mail)
}
// filter all email to get unique liste of email
var uniqueMailList = listOfEmails.filter((c, index) => {
return listOfEmails.indexOf(c) === index;
});
for(var i=0; i< uniqueMailList.length; i++){
// get mail of target i
var mail = uniqueMailList[i]
// filter table using mail of target i and status
var mailTable = new TableWithHeaderHelper(table)
.getTableWhereColumn("Status").matchValueRegex(/(New)/)
.getTableWhereColumn("Email").matchValue(mail);
// initialise html template
var htmltemplate=HtmlService.createTemplateFromFile("email")
htmltemplate.resource=resource
htmltemplate.status_r=status_r
htmltemplate.due_date_r=due_date_r
htmltemplate.link_r=link_r
var new_data = []
var htmlformail
// loop into the filtered table of target i only
for(var j=0; j< mailTable.length() ; j++){
// Any other value of column Target Value
var resource_col = mailTable.getWithinColumn("Resource").cellAtRow(j).getValue();
var status_col = mailTable.getWithinColumn("Status").cellAtRow(j).getValue();
var due_date_col = mailTable.getWithinColumn("Due Date").cellAtRow(j).getValue();
var link_col = mailTable.getWithinColumn("Link").cellAtRow(j).getValue();
new_data.push([resource_col,status_col,due_date_col,link_col])
}
htmltemplate.new_data=new_data
htmlformail=htmltemplate.evaluate().getContent()
var subjectMail = "Automation Support Services Actions Items";
var dt1 = new Date()
var dt2 = due_date_col
// get milliseconds
var t1 = dt1.getTime()
var t2 = dt2.getTime()
var diffInDays = Math.floor((t1-t2)/(24*3600*1000));
// 24*3600*1000 is milliseconds in a day
console.log(diffInDays);
// Send email
MailApp.sendEmail({
to:mail ,
subject: subjectMail,
htmlBody:htmlformail,
});
}
I'm not confident on the new_data.push([resource_col,status_col,due_date_col,link_col]), it's seems to be corect but I have no no way to verify that
Anyway thanks for using the utils script at https://github.com/SolannP/UtilsAppSsript, glad to see it help 👍

I want to use the content of a cell in a google sheet to control whether to send an e-mail out or not

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 working on this code to update google contacts with google forms and spreadsheet linked to it

I want this code to auto add contacts using trigger when form is submit but i get errors.
The code works properly with spreadsheet but I am not able get it work with forms.
I am kind of noob with coding.
So simple explanation would be helpful
Also contacts get add to "other" group in google contacts,is there any way to add them directly to "my contacts"?
function createHeaders() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Freezes the first row
sheet.setFrozenRows(1);
// Set the values we want for headers
var values = [
["First Name", "Last Name", "Email", "Phone Number", "Company", "Notes"]
];
// Set the range of cells
var range = sheet.getRange("A1:F1");
// Call the setValues method on range and pass in our values
range.setValues(values);
}
function createContact() {
var alreadyAdded = "Already added";
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:G3
var dataRange = sheet.getRange(startRow, 1, numRows, 8)
// 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 firstName = row[0]
var lastName = row[1]
var emailAddress = row[2]
var phone = row[3]
var company = row[4]
var notes = row[5]
var addedAlready = row[6];
if (addedAlready != alreadyAdded) {
// Create contact in Google Contacts
var contact = ContactsApp.createContact(firstName, lastName, emailAddress);
// Add values to new contact
contact.addCompany(company, "");
contact.addPhone(ContactsApp.Field.WORK_PHONE, phone);
contact.setNotes(notes);
sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
};
};
};
I was able to reproduce the error by passing one or more empty strings as arguments to the createContact() method:
var contact = ContactsApp.createContact("", "", "");
Check the values in your data array by logging them to see if you've got any empty strings there. You can wrap the code in a try block the prevent errors from stopping program execution. Any errors will be logged in a catch block
try {
var contact = ContactsApp.createContact(a, b, c);
}
catch(error) {
Logger.log(error);
}
I see you're trying to connect your Spreadsheet to Google Form. Check the Connecting to Google Forms
Apps Script allows you to connect Google Forms with Google Sheets
through Forms and Spreadsheet services. This feature can automatically
create a Google Form based on data in a spreadsheet. Apps Script also
enables you to use triggers, such as onFormSubmit to perform a
specific action after a user responds to the form.
you might be referring to onFormSubmit.
Here's the code demo for your reference.

Google Script Email loop

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.

Use Google Sheets Script to send email if cell value is null, then update cell value. If already populated, skip row

I am using google sheets script to send an email if not already sent.
colA: colN:
abc#gmail.com Yes
def#gmail.com
ghi#gmail.com Yes
I want my script to check the value of colB. If null, send the email then change the value to Yes. If not null, skip and proceed to next line. Here is what I have so far.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 23;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 13)
var data = dataRange.getValues();
for (var i=0; i < data.length; i++) {
var row = data[i];
// If Column N is null
if (data[i][13] === ""){
var emailAddress = row[0]; // First column of selected data
var message = "....." ; // Assemble the body text
var subject = ".....";
MailApp.sendEmail(emailAddress, subject, message);
data[i][13] = "Yes";
}
}
dataRange.setValues(data);
}
Any help would be greatly appreciated.
1) Your range has 13 columns, meaning that in JavaScript, the second array index runs 0...12. You are referring to 13, which is out of bounds.
2) As written, dataRange.setValues(data); writes over the entire dataRange. If the range contains formulas, they will be replaced by static values, which is undesirable. Otherwise, the content should stay the same as it was, except for the entries of data array that you changed. Still, if only a few values in a sheet change, it's better to update them individually, as shown below.
Instead of
data[i][12] = "Yes";
you can call
dataRange.offset(i, 12, 1, 1).setValue("Yes");