Send emails on Google form submission using specific variables - javascript

I am really new with this of Google scripts and I need your help.
I have a form that among the fields it has, it has one field named owner this is just a name.
I need to create a script to send a notification to the person that is listed in the owner field when the form is submitted.
I know how to burn an email directly on the script
function myFunction() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'This is your Alert email!'; // Second column
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
The problem I am lost with is that I know how to recognize the email depending on the name of the owner which is stored in another sheet.
Here is the link of a sample form and here is the sample spreadsheet
Can anyone share some light?

There are four things for you to understand and research.
1 - Create a script that can be created as an Installable "OnFormSubmit" trigger. Documentation is here.. This will execute every time a form is submitted. This is easy to do, and I have added a screenshot of the add trigger screen at the end of this answer.
2 - Learn about the information captured by an "OnFormSubmit" script. In particular it will return the range of the form submission from which you want the value of Column 7 (the Owner).
3 - The emails sheet contains a separate set of data. You can get it by referencing it with getSheetByName - documentation Ref
4 - You need to look for a match between "Owner and the "Name" value on the "Emails" sheet. There are many options for how to find a match with the owner but looping through the "emails" data is probably the easiest. At each new line you check whether the email name is a match for the "Owner". When you find a match, then you get the accompanying email address (in the cell beside the email name). Then you can send the email as you tested.
This code adapts your existing code to work through the steps mentioned.
function so5524531901(e) {
// this script as an Installable "OnFormSubmit" Trigger
//setup the spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//get the range from OnFormSubmit
var range = e.range;
//Logger.log("DEBUG: the range is "+range.getA1Notation());//DEBUG
// get the data for the range
var response = range.getValues();
// get the owner name from the form submission
var owner = response[0][7];
Logger.log("DEBUG: Owner = "+owner);// DEBUG
// get the emails list
var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails");
// get ALL the data from this sheet
var emaildata = emailSheet.getDataRange().getValues();
// check how many rows of data
var emailLastRow = emailSheet.getLastRow();
// start the loop through the emails data
for (var i=1; i<emailLastRow; i++){
// if owner is equal to Email Name
if (owner == emaildata[i][0]){
// there is a match
//get the email address
var emailAddress = emaildata[i][1];
Logger.log("DEBUG: owner = "+emaildata[i][0]+", email address: "+emailAddress);// DEBUG
// Send Alert Email.
// Uncomment the following rows to declare the message, subject and then send the email.
// var message = 'This is your Alert email!'; // Second column
//var subject = 'Your Google Spreadsheet Alert';
//MailApp.sendEmail(emailAddress, subject, message);
}
}
}

Related

Trying to create a script that would send an email to multiple users on a spreadsheet, im a complete beginner to Google Apps Script

I am trying to create a function and add a trigger to send an email for every email address added on a spreadsheet, and I am facing a couple of difficulties.
This is the script so far:
function sendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Incident name/scenario").getRange("R2:R100")
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'You have been mentioned on the spreadsheet.';
// R Column
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
I want every time an email address is entered on column R for it to send an email to the mentioned person. So far it only works if I enter an email on R2, as I understood I need to create some sort of loop, however not sure how to approach this, as I don't want it to resend to every person on column R when a new email is entered.
If I tried to choose getValues() instead of getValue() I would get an error considering it works differently.
Is there a way to also restrict it to send emails that end with a specific way, and skip any emails that don't match without causing any errors, i.e. "#michael.com" , "#recreat.com" etc.
Lets say that you a table of emails like this:
A
1
Emails
2
email1
3
email2
4
email3
5
email4
6
email5
7
email6
8
email7
9
email8
10
email9
11
email10
All you have to do is
function getEmails() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const emails = sh.getRange(2,1,sh.getLastRow() - 1).getValues().flat().join(",");
return emails;
}
Then in your email script:
GmailApp.sendEmail(getEmails(),....
creating markdown tables
google-apps-script reference
javascript reference
Learn More

Google Sheet script - Automatically send an email with values when they are added to a Google Sheet

I've been trying to follow the document below but have got a bit stuck. In short, I am trying to have a Google Sheet send out an email automatically when two values are added to a Google Sheet (Name, Telephone)
The function below works great when I run it from App script but I am looking for it to grab the values that are inserted at the time and send the email automatically rather than having to run the script each time in App Script.
// Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your Alert email!'; // Second column
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
https://www.groovypost.com/howto/google-sheets-send-email-based-on-cell-value/
You need to use the onEdit feature.
https://developers.google.com/apps-script/guides/triggers/events
function onEdit(e){
sendEmailToUpdatedValue(e)
}
function sendEmailToUpdatedValue(e){
let email_x = /\b[\w\.\-\+]+#[\w\-]+\.[a-zA-Z]{2,13}(\.[a-zA-Z]{2,13}|\b)/;
let email = e.range.getValue();
let is_email = email_x.test(email);
if(is_email){
//your email function here
}
}
Be sure to run the onEdit function once within Apps Script in order to ensure the trigger is set up. That first time will get an error.
Keep in mind that onEdit only fires from a user action, so if the emails are being added from a form or some other script, this will not work. In those scenarios you would need a time based trigger.

Bad Value, Constant Error

I am a brand new coder, and I want my code to work with this process:
I fill out a form that leads to a spreadsheet
I want that spreadsheet to check certain values in another spreadsheet to see if they match (there are lots of values in that spreadsheet and I want the program to run through the whole column)
If they match, I want to have an email sent to me with the matching person's name, which is displayed in the same row in the spreadsheet I will be comparing to.
My not working code:
function myFunction(e) {
var genderSheet1 = e.values[19];
var genderSheet2 = SpreadsheetApp.openById("To Populate");
if (genderSheet1===genderSheet2) {
var userName = e.values[1];
var userEmail = "email";
var subject = "WORKER FOUND?";
var message = "Dear " + userName + "," +
"\n\n\nThis is the finder" +
MailApp.sendEmail(userEmail, subject, message, {attachments:file.next().getBlob()});
}
}
Please help!
I will go based on a few assumptions
Your code has an alteration in SpreadsheetApp.openById("To Populate") and To Populate is a real ID in the actual code and not "To Populate" as is written here
You have set a trigger to execute the script on Form submit in the script triggers
I also note that you have not mentioned what the problem is so I will have to point out some of the problems in your code as I see it.
First of all var genderSheet1 = e.values[19]; will be a string value, while var genderSheet2 = SpreadsheetApp.openById("To Populate"); is an object, so if (genderSheet1===genderSheet2) will always return a false.
Then we have this bit MailApp.sendEmail(userEmail, subject, message, {attachments:file.next().getBlob()}) however, there is no file defined anywhere in the code. The syntax you are using would indicate that you should have a DriveApp method that returns a fileIterator object. What is the attachment you are trying to send?
Please refer to the form submit trigger event objects in the documentation to see what you should expect when using that event handler.

onFormSubmit trigger not working in google script

I wonder if someone can help me.. I've written this code which is supposed to carry out the following workflow:
user fills in the form, form responses are recorded in excel sheet and various calculations take place, final values are appended into a template pdf, and this pdf is sent via email to the user.
The script does do all of that but only when I manually click "run", whereas I want it to execute whenever a form is submitted and I can't understand why it doesn't.
I would add a screenshot of my trigger but I can't as I don't have 10 reputation yet; but my trigger is set up as follows:
Run: onFormSubmit
Events: From spreadsheet, On form submit
I'll paste my code below, does anyone have any ideas as to why it might not be working? Any help would be hugely appreciated.
//Set out global variables
var docTemplate = ("1Ff3SfcXQyGeCe8-Y24l4EUMU7P9TsgREsAYO9W6RE2o");
var docName=("Calculations");
function onFormSubmit(e){
//Variables
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
//Template Info
var copyId=DriveApp.getFileById(docTemplate).makeCopy(docName+' for '+userEmail).getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
//Putting the data into the file
copyBody.insertParagraph(1,'Total Outstanding Principal Debt: £' + totalOutstandingPrincipalDebt);
copyBody.insertParagraph(2,'Total Outstanding Interest: £'+ totalOutstandingInterest );
copyBody.insertParagraph(3,'Total Outstanding Compensation: £'+ totalOutstandingCompensation);
copyBody.insertParagraph(4,'Grand Total: £' + grandTotal);
copyBody.insertParagraph(5,'Daily Interest Rate: £'+ dailyInterestRate);
copyDoc.saveAndClose();
//email pdf document as attachment
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var subject = "Calculations";
var body = "Thank you very much for using our online calculator. Please find your results attached.";
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
//Deletes temporary Document
DriveApp.getFileById(copyId).setTrashed(true);
}
It looks like instead of using the values attribute of the form submit event you are trying to look directly at the spreadsheet tab that gets values written to it. Think of it this way: you could attach this script to a Form instead of a spreadsheet and have it still work. At the time a form submission happens, the event object e has everything you need.
This is a problem because you have hardwired cell addresses, but the form will keep writing more rows. This means you won't see new rows as they accumulate.
But the big problem is that you're looking at that tab using getActiveSpreadsheet(). When a user submits a form response, there is no "active spreadsheet." The "active" thing was the form. So, in order to get the data that was submitted, you'll need to look in e.values -- this will contain the row of data you're currently trying to get to in lines 9-14.
btw, the reason it works when run manually is because "active spreadsheet" means something. As soon as you walk away, that spreadsheet isn't active.
EDIT:
Zehrazjp20 points out that they are using the spreadsheet for computation, not just reading raw values as from the Form Submit event. In this case, the best way is to replace:
var ss = SpreadsheetApp.getActiveSpreadsheet();`
with
var ssID = 'abcdefghijklmnop';
var ss = SpreadsheetApp.openById(ssID);
...using your spreadsheet's real ID, of course.

Creating email script to send from different email addresses based on user answer choices

I work for an organization which has a GAFE account. Multiple users within our organization collaborate on projects, and we have run into a problem when writing email scripts.
We use GForms to collect survey data from users (both teachers and students) within our organization. Depending on the answer choice selected in the form, we want emails to be sent from different email accounts.
For example, we have a reading log that asks 3 questions: title of the book, if the user is a student or teacher, and the user's email address. (The last question is optional, to be completed if the user wants an email confirmation of their submission information. As a result, this field is sometimes blank.) If the user is a TEACHER, we want an email to be sent from an ADMINISTRATOR. If the user is a STUDENT, we want an email to be sent from the LIBRARIAN. (Note: I am neither of these individuals.)
What we tried: In the GSheet which contains the responses to the form, I wrote an email script while logged into my account and saved it. I shared that GForm with both the Administrator and Librarian. Both the Administrator and the Librarian log in, copy the script, make their own with customized fields using an IF statement, then set the trigger for only their customized script.
The problems:
(1) The resulting emails come from BOTH the Administrator and the Librarian, no matter if the user is a teacher or student.
(2) An error report gets sent when the user does not supply an email address (which is optional in the form).
This is the script I made that is copied & pasted into new script files:
function emailScript(e) {
var timestamp = e.values[0]; // Column A data in responses spreadsheet
var user = e.values[1]; // Column B data in responses spreadsheet
var email = e.values[2]; // Column C data in responses spreadsheet
var book = e.values[3]; // Column D data in responses spreadsheet
var subject = "Confirmation of Book Log Submission";
var emailBody = "Thank you for submitting " + book + "to the online book log." ;
//if (user == "Student"){ MailApp.sendEmail(email, subject, emailBody)};
//if (user == "Teacher"){ MailApp.sendEmail(email, subject, emailBody)};
}
The Librarian deletes the "//" at the beginning of the 1st If statement. The Administrator deletes the "//" at the beginning of the 2nd If statement.
What we want is ONE EMAIL sent. Each teacher gets an an email from the Administrator, and each student gets an email from the Librarian.
Any help is appreciated.

Categories

Resources