Send email when cell contains a specific value - google-apps-script

I am working on a Google Form that allows our employees to submit an in-field inspection of their equipment. I have a script that takes the form responses and creates a new sheet based on the date and the specific unit number of the equipment. The user goes through a checklist and selects either "Good" or "Needs Repair" for each item on the list. They can also add comments and upload pictures of any issues.
I am trying to have the script automatically send an email if "Needs Repair" is selected for any of the checks, as well as if the user adds a comment or a picture. This way we do not have to open every submitted sheet to know if any repairs are required. What I have is just not sending emails and I cannot figure out why. Any help is greatly appreciated!
Here is my current script:
function onFormSubmit() {
// onFormSubmit
// get submitted data and set variables
var ss = SpreadsheetApp.openById("*Spreadsheet Link*");
var sheet = ss.getSheetByName("Submissions");
var row = sheet.getLastRow();
var Col = sheet.getLastColumn();
var headings = sheet.getRange(1,1,1,Col).getValues();
var lastRow = sheet.getRange(row, 1, 1, Col);
var UnitNumber = sheet.getRange(row,3).getValue();
var newSheet = sheet.getRange(row,4,Col).getValue();
var fileExist = false;
var drillSheet = null;
var folder = DriveApp.getFoldersByName("Fraser Drill Inspections").next();
var files = folder.getFilesByName(UnitNumber);
var file = null;
var employee = sheet.getRange(row,2);
var checks = sheet.getRange(row, Col, 1, 20);
// check if Drill has sheet
while (files.hasNext())
{
fileExist = true;
file = files.next();
break;
}
if (fileExist) //If spreadsheet exists, insert new sheet
{
drillSheet = SpreadsheetApp.openById(file.getId());
drillSheet.insertSheet("" + newSheet);
}
else //create new spreadsheet if one doesn't exist
{
drillSheet = SpreadsheetApp.create(UnitNumber);
var ssID = drillSheet.getId();
file = DriveApp.getFileById(ssID);
file = file.makeCopy(UnitNumber, folder);
DriveApp.getFileById(ssID).setTrashed(true);
drillSheet = SpreadsheetApp.openById(file.getId());
drillSheet.renameActiveSheet(newSheet);
}
// copy submitted data to Drill sheet
drillSheet.getSheetByName(newSheet).getRange(1,1,1,Col).setValues(headings);
drillSheet.appendRow(lastRow.getValues()[0]);
drillSheet.appendRow(['=CONCATENATE(B6," ",B5)']);
drillSheet.appendRow(['=TRANSPOSE(B1:2)']);
//Hide top rows with raw data
var hiderange = drillSheet.getRange("A1:A3");
drillSheet.hideRow(hiderange);
//Widen columns
drillSheet.setColumnWidth(1,390);
drillSheet.setColumnWidth(2,700);
//Send email if there are any comments or if anything needs repair
if(lastRow.getValues() == "Needs Repair") {
function SendEmail() {
var ui = SpreadsheetApp.getUi();
MailApp.sendEmail("email#domain.com", "Drill Needs Repair", "This drill requires attention according to the most recent inspection report.")
}
}
}

The function to send an email is:
GmailApp.sendEmail(email, subject, body);
Try changing
if(lastRow.getValues() == "Needs Repair") {
function SendEmail() {
var ui = SpreadsheetApp.getUi();
MailApp.sendEmail("email#domain.com", "Drill Needs Repair", "This drill requires attention according to the most recent inspection report.")
}
}
to just the following:
if(lastRow.getValues() == "Needs Repair") {
GmailApp.sendEmail("youremail#domain.com", "Drill Needs Repair", "This drill requires attention according to the most recent inspection report.");
}
It looks like you've still got some additional work to do too, e.g. to make it send to the email address from the form submission instead of a hardcoded one.

Related

Is there a way to pass information to a Google Form from a link sent in an email (parameters in the URL maybe)?

I want to send an email to folks using a script that will ask them to confirm an appointment. I'd like to make it easy for them to confirm. I was thinking I could have a link go to a Google Form, but I would like that form to contain information about the appointment; I thought about putting parameters in the form URL (e.g. https://docs.google.com/forms/d/e/[formID]/viewform?location=Office1&subject=management) but I don't see a way to grab that URL in the script attached to the form (only the normal URL of the form). Any way I can get the URL with the parameters? Or is there some other way to pass information to the form? (Or, failing that, to a Google Doc or something?)
I tried using getPublishedURL but that gets the standard URL, no parameters...
Question: Is a way to pass parameter information to a Google Form from a link sent in an email.
Answer: No.
But there is a way that you can use a Google Forms link, sent in an email, that would enable a person to confirm an appointment.
In brief:
create a Google Form with three questions
Question 1 = Title: "User Details", Type: "Paragraph Text"
Question 2 = Title: "My appoitment time is", Type: "Short-answer Text"
Question 3 = Title: "Acknowledgement", Type: "List Item", one options = "yes"
create a Google spreadsheet with two sheets
sheet 1 = user details = name, email, appointment time plus two checkboxes ("ResponseCreated" and "Email sent")
sheet 2 = Form Responses - linked from the Google Form
add one additional column: "EditResponse URL"
write/run a script to create form responses using the data on sheet1
this will populate questions 1 and 2
Sheet 2(Form Responses) is automatically updated.
write/run a script to create the EditResponseUrl for the data on sheet="Form Responses"
write/run a script to send emails to the user details on Sheet1
use the EditResponseUrl from sheet 2 to create an HTML link in the email
-when each user clicks the link in their email, they are directed to a form that contains their details, and the time of their appointment.
They select "Yes" (to acknowledge the appointyment) and then Submit.
Sheet 2 is automatically updated from the form - this is your evidence of their acknowledgement.
Create Form Responses
function createResponse() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sourceSheetName = "User details"
var source = ss.getSheetByName(sourceSheetName)
// get the number of entries
var aVals = source.getRange("A2:A").getValues()
var aLast = aVals.filter(String).length
// get the data; 3 columns plus a checkbox// one row = header
var sourceRange = source.getRange(2,1,aLast,4)
//Logger.log("DEBUG: source range = "+sourceRange.getA1Notation())
var sourceValues = sourceRange.getValues()
var formUrl = ss.getFormUrl();
var form = FormApp.openByUrl(formUrl); // grabs the connected form
var questions = form.getItems();
// Getting the fields of the form questions
var userInfo = questions[0].asParagraphTextItem();
var appntInfo = questions[1].asTextItem();
var updateArray = new Array
for(i = 0; i < sourceValues.length; i++) {
if (sourceValues[i][3] == false){
var formResponse = form.createResponse();
var d1 = "Name: "+sourceValues[i][0]+"\nEmail address: "+sourceValues[i][1]
var r1 = userInfo.createResponse(d1)
var d2 = sourceValues[i][2]
var r2 = appntInfo.createResponse(d2)
formResponse.withItemResponse(r1)
formResponse.withItemResponse(r2)
formResponse.submit()
updateArray.push([true])
}
else {
updateArray.push([true])
}
}
// Logger.log("DEBUG: checkbox range = "+source.getRange(2,4,sourceValues.length).getA1Notation())
// Logger.log(updateArray) // DEBUG
source.getRange(2,4,sourceValues.length).setValues(updateArray)
}
Get EditResponseUrl
function responseURL() {
var form = FormApp.openById('10cG91VSwmIvCS8PQbJwtrQk47uWVmcH6i5pX83KsuVE')
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Form Responses 1')
var formResponses = form.getResponses()
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i]
sheet.getRange(i+2, 5).setValue(formResponse.getEditResponseUrl());
}
}
Send email
function sendEmails(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var userSheetName = "User details"
var usersheet = ss.getSheetByName(userSheetName)
var formSheetName = "Form Responses 1"
var formsheet = ss.getSheetByName(formSheetName)
// get the number of entries
var aVals = usersheet.getRange("A2:A").getValues()
var aLast = aVals.filter(String).length
// get the data; 3 columns// one row = header
var userRange = usersheet.getRange(2,1,aLast,5)
// Logger.log("DEBUG: source range = "+userRange.getA1Notation())
var userValues = userRange.getValues()
var formRange = formsheet.getRange(2,1,aLast,5)
// Logger.log("DEBUG: form range = "+formRange.getA1Notation())
var formValues = formRange.getValues()
//Logger.log(formValues)
// return
var sentArray = new Array
var emailSubject = "Request for Confirmation of Appointment"
for (var i=0;i<userValues.length;i++){
if (userValues[i][4] == false){ // test if email has already been sent
var name = userValues[i][0]
var email = userValues[i][1]
var apptTime = userValues[i][2]
var respURL = formValues[i][4]
var html_link = "<a href='"+respURL+"'> our Appointment confirmation form</a>"
//Logger.log(html_link)
var html_body = "Hello, "+ name +",<br><br>"
+ "Your appointment is at "+apptTime+". Would you please confirm your appointment by going to " + html_link + ".<br><br>"
+ "Thank you, <br>"
+ "Signature"
MailApp.sendEmail({
to: email,
subject: emailSubject,
body: "Can add a Plain Text version of the email body here for email apps that dont do html",
htmlBody: html_body
})
sentArray.push([true])
Logger.log("mail sent to "+name)
}
else{
sentArray.push([true])
}
}
usersheet.getRange(2,5,userValues.length).setValues(sentArray)
}
User Details (sheet1)
Form Responses (sheet2)
Email
Form - Confirm appointment

Pushing a simple Log string from a Google Ad Script to a Google Sheet

I am trying to set up a script which can push data from an App Script into a Google Sheet.
I have the script successfully logging what I want, which goes in the following format Account budget is 12344, but now I want to push this into a Google Sheet. I have set up a variable containing the URL and another variable containing the sheet name, and also a clear method to delete anything already there.
Find the code I have below:
// - The link to the URL
var SPREADSHEET_URL = 'abcdefghijkl'
// - The name of the sheet to write the data
var SHEET_NAME = 'Google';
// No to be changed
function main() {
var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = spreadsheet.getSheetByName(SHEET_NAME);
sheet.clearContents();
}
function getActiveBudgetOrder() {
// There will only be one active budget order at any given time.
var budgetOrderIterator = AdsApp.budgetOrders()
.withCondition('status="ACTIVE"')
.get();
while (budgetOrderIterator.hasNext()) {
var budgetOrder = budgetOrderIterator.next();
Logger.log("Budget Order Amount " + budgetOrder.getSpendingLimit());
}
}
Assuming you want to clear the entire Sheet every time you extract the data this should work for you. You will need to set the url and shtName variables.
function getActiveBudgetOrder() {
var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxx/';
var shtName = 'Sheet1';
var arr = [];
var sht = SpreadsheetApp.openByUrl(url).getSheetByName(shtName);
// There will only be one active budget order at any given time.
var budgetOrderIterator = AdsApp.budgetOrders()
.withCondition('status="ACTIVE"')
.get();
while (budgetOrderIterator.hasNext()) {
var budgetOrder = budgetOrderIterator.next();
arr.push(["Budget Order Amount " + budgetOrder.getSpendingLimit()]);
}
sht.clearContents();
sht.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}

Templated email using Apps Script based on data in Google Sheets

I'm new to scripting so I hope someone can help me create one.
I'm trying to create a script for a sheet that can send an email when a custom menu is pressed.
Here's a file to work on.
https://docs.google.com/spreadsheets/d/1Ea-3eZoclHrAkZLwRmWWFbmbnn4dESNWvK_6pn1DCbE/edit?usp=sharing
Also, it should only send it if a column (ex. Column I) has a specific Value like 'Approved'
Email content should look like:
Subject: Leave Application # 'ColumnC'
Hi 'ColumnA',
We received your 'ColumnB' request for 'ColumnE'
Status: 'ColumnG'
More Details: 'ColumnH'
-Admin
Email should be sent to Column E and F.
The script must also update the spreadsheet to avoid duplicate emails.
Here is the working example
Here is the code:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var startRow = 2; // First row of data to process
var lastRow = sheet.getSheetByName('Journal').getLastRow(); // Last row with content
var rangeEmailSent = sheet.getRangeByName('Journal!EmailSent');
var dataEmailSent = rangeEmailSent.getValues();
var dataRequestedBy = sheet.getRangeByName('Journal!RequestedBy').getValues();
var dataRequestType = sheet.getRangeByName('Journal!RequestType').getValues();
var dataRefNo = sheet.getRangeByName('Journal!RefNo') .getValues();
var dataStatus = sheet.getRangeByName('Journal!Status') .getValues();
var dataToEmail = sheet.getRangeByName('Journal!ToEmail') .getValues();
var dataSupComment = sheet.getRangeByName('Journal!SupervisorComment').getValues();
var subjectTemplate = sheet.getRangeByName('SubjectTemplate1').getValue();
var bodyTemplate = sheet.getRangeByName('BodyTemplate1').getValue();
var msgSubject;
var msgBody;
for (var i = (startRow-1); i <= (lastRow-1); i++) {
// send e-mail if "Email Sent" is not blank and if "Status" is not empty
if ( !(dataEmailSent[i]=='Yes') && !(dataStatus[i] =='')) {
msgSubject = subjectTemplate.replace('$REF$', dataRefNo[i]);
msgBody = bodyTemplate
.replace('$REQUESTED_BY$', dataRequestedBy[i])
.replace('$REQUEST_TYPE$', dataRequestType[i])
.replace('$EMAIL$', dataToEmail[i])
.replace('$STATUS$', dataStatus[i])
.replace('$SupervisorComment$', dataSupComment[i]);
// Logger.log(msgSubject);
// Logger.log(msgBody);
MailApp.sendEmail(dataToEmail[i], msgSubject, msgBody);
// Change "Email sent" to "Yes"
rangeEmailSent.getCell(i+1,1).setValue('Yes'); // note: getCell(1,1) refers to the 1st cell
}
}
}

How to get ID value of Google Drive file for input to Google Apps Script

I am writing a Google Apps script to send a file from Google Drive to a list of email addresses saved in a Google Spreadsheet.
Since I will be sending a different file every time I use the script, I have my script set up to take the file ID as text input from the user. The only way I've seen to get the ID directly from Drive is to right-click on the file, select "Get Link", copy it to the clipboard, paste it into my form and erase the bits that aren't the ID. I'm writing to ask if anyone knows a better way. I'm also open to comments suggesting a better program design.
function sendEmails() {
var id = "gibberish"; //email spreadsheet
SpreadsheetApp.openById(id);
var sheet = SpreadsheetApp.getActiveSheet();
Logger.log(sheet.getName());
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Get subject line from user
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Enter subject: ', ui.ButtonSet.OK_CANCEL);
var subject;
// Process the user's response. TODO- error checking
if (response.getSelectedButton() == ui.Button.OK) {
subject = response.getResponseText();
} else {
Logger.log('The user either canceled or clicked the close button in the dialog\'s title bar.');
subject = "No subject";
}
//get id for attachment file
var ui2 = SpreadsheetApp.getUi();
var response2 = ui2.prompt('Enter Drive id for attachment: ', ui.ButtonSet.OK_CANCEL); //TODO- error checking
var attachmentID;
var file = null;
if (response2.getSelectedButton() == ui.Button.OK) {
attachmentID = response2.getResponseText();
file = DriveApp.getFileById(attachmentID);
Logger.log('The user entered %s', response2.getResponseText());
} else {
Logger.log('The user either canceled or clicked the close button in the dialog\'s title bar.');
}
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = "Time Sheet attached. \n\n -Jessica";
if (file != null) { //TODO- or if file is right file
MailApp.sendEmail(emailAddress, subject, message, {attachments: [file]});
} else {
Logger.log("No file was attached. Email not sent.");
}
}
}
This isn't mine, we've all passed it around this forum quite a bit.
this one works because it gets what you want regardless of if the person pastes in the id or the url:
function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }
so you don't need to be picky about erasing the rest of the url yourself.
I did something similar in my Copy Folder script.
Basically, I parsed the form input in javascript to select only the folder ID. With this code, you can actually pass in the "Sharing ID" (retrieved by the Right-click and "Get Link" method), the folder URL (retrieved by the browser address bar when you are inside the folder in Google Drive), or just the folder ID. The javascript parses the input and replaces the form entry with just the folder ID, so that your Google Script can retrieve this form data normally.
You can view the source code for the project, but here is the relevant part. In my web app, this is located in the JavaScript.html file.
// Regular expression - find string beginning with "id="
// http://www.w3schools.com/jsref/jsref_regexp_source.asp
var regex = /id=/;
// NOTE: pretty sure you could just make a string variable = "id=" instead of regex, but I didn't want to mess up my script
// Set a temporary variable to the value passed into the "folderId" field
var fId = thisForm.folderId.value;
// Get the index of the string at which the folderId starts
var idStart = fId.search(regex);
var foldersStart = fId.search("folders");
if (idStart > 0) {
// Slice the string starting 3 indices after "id=", which means that it takes away "id=" and leaves the rest
fId = fId.slice(idStart+3);
} else if (foldersStart > 0) {
fId = fId.slice(foldersStart + 8);
}
// Find the ampersand in the remaining string, which is the delimiter between the folderId and the sharing privileges
var amp = fId.indexOf("&");
// Slice the string up to the ampersand
if (amp > 0) {
fId = fId.slice(0,amp);
}
// Set the folderId element within thisForm (retrieved from doGet) to the new, sliced fId variable
thisForm.folderId.value = fId;

get form URL from a spreadsheet bound Form

In a spreadsheet script I want to send mail to users that will point them to the URL of a form that will let them enter data. I have tried:
function test1(){
var formID = FormApp.getActiveForm();
var formUrl = DriveApp.getUrl(formID);
sendMail(formUrl);
return
}
This fails because the value of formID is allways NULL.
If there is one form linked to spreadsheet
Use
var ss = SpreadsheetApp.getActiveSpreadsheet(); // or openById, etc
var formUrl = ss.getFormUrl();
to get its Url. If needed, FormApp.openByUrl(formUrl); returns a pointer to the form, which allows any other methods.
Multiple forms linked to spreadsheet
There is no built-in method to return the list of forms linked to a given spreadsheet; this is an open issue in Apps Script issues tracker. A workaround is to search all forms (as Cyrus Loree did), get the destination of each, and return the list of those where the destination is the spreadsheet of interest. This is how:
function linkedForms() {
var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var formList = [];
var files = DriveApp.getFilesByType(MimeType.GOOGLE_FORMS);
while (files.hasNext()) {
var form = FormApp.openByUrl(files.next().getUrl());
try {
if (form.getDestinationId() == ssId) {
formList.push(form.getPublishedUrl());
}
}
catch(e) {
}
}
return formList;
}
Remarks:
I put form.getDestinationId() in a try block because this method throws an error what the form's destination spreadsheet happens to be deleted (instead of just returning null)
To get the list of form Ids instead of Urls, use form.getId() in the function.
Because you are working in the Spreadsheet, you need to get the associated form from the Spreadsheet object (e.g. SpreadsheetApp.getActiveSpreadsheet.getFormUrl() ).
You will also need to send the mail message with the htmlBody optional parameter.
Here is a code sniplet:
function sendNotice(recipient){
try{
// either hardcode the folder id below
var formStorageFolderId = '';
// or programmatically get the folder from the spreadsheet parent
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssFolder = DriveApp.getFileById(ss.getId()).getParents();
if(ssFolder.hasNext()){
// assume there is only one parent folder
formStorageFolderId = ssFolder.next().getId();
}
var formFolder = DriveApp.getFolderById(formStorageFolderId);
var files = DriveApp.getFilesByType(MimeType.GOOGLE_FORMS);
var formId = '';
while(files.hasNext()){
// search for the form (is it the same name as the spreadsheet?)
var file = files.next();
var fileName = file.getName();
var sheetName = ss.getName();
if(fileName == sheetName){
// matched names
formId = file.getId();
break;
}
}
if(formId){
var actualForm = FormApp.openById(formId);
var formName = actualForm.getTitle();
var formURL = actualForm.getPublishedUrl();
var subject = "Please fill out form";
// html mail message (needed for the link
var mailBody = '<div><p>Please fill out the attached form<p>';
mailBody += '<p>' + formName + '';
MailApp.sendEmail(recipient, subject, '',{htmlBody:mailBody});
}
}catch(err){
Logger.log(err.lineNumber + ' - ' + err);
}
}
I know that it's an old question, but I'll still add an answer to whom it may concern. #user3717023's answer works fine, but for most use-cases, there's a better way.
Generally speaking, Form is connected to Sheet, not to Spreadsheet itself. So, one way to get all of the Spreadsheet forms is to go through the Sheets of the Spreadsheets, and get their Form URL, like that:
function getFormsOfSpreadsheet(spreadsheetId) {
const ss = SpreadsheetApp.openById(spreadsheetId);
const sheets = ss.getSheets();
const formsUrls = [];
for (const sheet of sheets) {
const formUrl = sheet.getFormUrl();
// getFormUrl() returns null if no form connected
if (formUrl) {
formsUrls.push(formUrl);
}
}
return formsUrls;
}
Docs
If this way is not optimal for you (e.g. you have way too many Sheets in your Spreadsheet and only a few of them are linked to Forms), there's still a possibility that the Forms you need to capture are stored in the same Folder. In this case, there's no need to search through the whole Drive to capture them, you can use the same method, but with Folder:
function linkedForms() {
var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var formList = [];
var folder = DriveApp.getFolderById(yourFolderId);
var files = folder.getFilesByType(MimeType.GOOGLE_FORMS);
while (files.hasNext()) {
var form = FormApp.openByUrl(files.next().getUrl());
try {
if (form.getDestinationId() == ssId) {
formList.push(form.getPublishedUrl());
}
}
catch(e) {
}
}
return formList;
}
Docs