Auto Email google sheet response - google-apps-script

Can anyone help with a google app script to trigger an auto email to applicants that failed the quiz - scoring lower than 130 on column A on google sheets?
Thanks in advance for the help!
Quiz Results Response

Do you want the mail to go automatically as soon as the form is filled? In that case, you can use the onFormSubmit trigger to send the mail to him automatically.
If you are processing the answers and then creating the result sheet, you can send the mail from the result sheet by processing each row in the sheet. You can easily find many examples how to send a mail from a sheet based on value in a column.
I am enclosing a similar code which sends the response to a user automatically as soon as he submits a form. I am storing his email ID (based on employee number) and sending him some data (based on his employee number) as soon as requests it. It works as a "employee self help portal".
function onFormSumbit(e) {
var emp = e.source.getActiveSheet().getRange(e.range.rowStart,2).getValue();
var lvss = SpreadsheetApp.openById("xxxx"); // blanks https://docs.google.com/spreadsheets/d/1kjOjhH0dvz4j3FsB_1UR5astpy8-ZxszNI4BZo4XJP0/edit#gid=0
SpreadsheetApp.setActiveSpreadsheet(lvss);
var lvsht = lvss.getSheetByName("Blanks");
var lvlr = lvsht.getLastRow();
var vA =lvsht.getRange("A:L").getValues();
var html="<style>th,td{border:1px solid black;}</style><table>";
html+='<tr>';
for(var i=0;i< 4 ;i++) {//make title
html+=Utilities.formatString('<th>%s</th>',vA[0][i]);
}
html+='</tr>';
for (i=1;i<lvlr;i++){
if (vA[i][0]==emp){
html+='<tr>';
for (j=0;j<4;j++) {
if ( j==2 ){
vA[i][j]=Utilities.formatDate(vA[i][j],"GMT+05:30", "dd-MM-yy");
}//if date
html+=Utilities.formatString('<td>%s</td>',vA[i][j]);
}//for emp
html+='</tr>';
}//if
}//for
html+='</table><br>';
var empss = SpreadsheetApp.openById("xxxx"); // emp master
SpreadsheetApp.setActiveSpreadsheet(empss);
var empsht = empss.getSheetByName("Emp");
var emplr = empsht.getLastRow();
var empvals =empsht.getRange("A:H").getValues();
for (i=1;i<emplr;i++){
if (empvals[i][0]==emp){
var em1=empvals[i][7];
var name=empvals[i][1]
break;
}//if
}//for
var subject="Your punch blanks "+name;
if (em1=="") {} else {
//MailApp.sendEmail(em1, subject, html);}
MailApp.sendEmail({
to: em1,
subject: subject,
htmlBody: html
});
}
}
//
//
Hope it helps !!

This function processes the full spreadsheet data from first row to last row and sends failure notification emails where the score is less than 130 ...
function notifyFailedCandidates ()
{
//Get the active sheet from the current spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get all the rows from the spreadsheet
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,1, lastRow-1, lastColumn);
var rows = searchRange.getValues();
//loop through each of the rows
for (var rowNumber in rows)
{
//Get each of the values from the row
var quizScore = rows[rowNumber][0];
var firstName = rows[rowNumber][1];
var lastName = rows[rowNumber][2];
var email = rows[rowNumber][3];
//Send a failure notification if the score is less than 130
if (parseInt (quizScore) < 130)
{
MailApp.sendEmail
(
email, //candidate email address
'Notification of test failure', //Subject of failure notification email
//Contents of failure notification email
'Hi ' + firstName + "\n\n" +
'This email is to let you know that unfortunately you failed the test, with a score of ' + quizScore + ' / 170' + "\n\n" +
'Better luck next time'
);
}
}
}

Related

Google Script: sending email as thread instead of individual emails

Currently have this script to send out approval request emails to relevant approvers. However would want for this to be sent out as a thread instead of spamming individual emails. Is there anything I could insert into my script to help with this? Thanks in advance!
function sendEmail(){
//drawing from the active sheet.
var sheet = SpreadsheetApp.getActiveSheet();
//setting variables & getting the data from the sheet you are on
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn(); //Number of columns to process
var dataRange = sheet.getRange(startRow, 1, numRows-(startRow-1), numColumns);
var data = dataRange.getValues();
var complete = "sent";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var aemail = row[16]; //approver’s email
var approval = row[13]; //approval column
var reqrow = row[17]; //req row number
var emailed = row[18]; //already emailed
//check to see if an email has NOT been sent
if (emailed != complete){
//check to see if not yet approved
if(approval == ""){
//When done, it will mark it as sent in the last column
var sent = sheet.getRange(startRow + i, numColumns);
//Setting it to send the email to the approver's email
var email = aemail;
//Change the text as desired
var subject = "Quotation Request";
// \n is a line break
var emailtext = "Hi, " +
"\n\nYou have quotation request pending your review and approval on row " + reqrow + ".\n" +
"\nPlease go to the link below for your further action.\n" +
"\nhttps://docs.google.com/spreadsheets/d/x123/edit?usp=sharing \n" +
"\nThis is an automated email. Thanks."
//Send the email
GmailApp.sendEmail(email, subject, emailtext);
//Assign “sent” to to the last cell in the row so the email does not send again
sent.setValue(complete);
}
}
}
}
You would need to add parameter Message-Id in every email to achieve threading in recipient's mailbox.
However, GmailApp.sendEmail does not support this feature.
https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String)

Sending automatic emails to specific email addresses once rows are edited in google sheet

I'm new to g-scripts and facing some issues in coming up with the code for the below. My goal is:
Want to send an automatic email to specific people once the information in any of the rows in the google sheet are edited.(note: the range is the whole sheet)
For each row in the google sheet, there's an email address next to it (under a new column) which specifies the person this automatic email should be sent to.
Can the changes be compiled once per day and sent via 1 email per email address?
Thank you in advance for your help.
Currently, this is my code:
function onEdit(e){
var rows = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1").getRange(30000,30).getValue();
var headerRow = rows.shift();
var editedRow = e.range.getRow();
var template = HtmlService.createTemplateFromFile("Template1.html");
template.headerRow = headerRow;
template.editedRow = editedRow;
template.rows = rangeValues;
var html = template.evaluate().getContent();
function sendEmails(){
var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1").activate();
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr=ss.getLastRow();
//getting email body:
var sheet2Text = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet2").getRange(1,1).getValue();
// Logger.log(emailText);
var quotaLeft = MailApp.getRemainingDailyQuota();
Logger.log(quotaLeft);
if((lr-1)>quotaleft){
Browser.msgBox("You have"+quotaLeft+"left & you're trying to send"+(lr-1)+"emails. Emails not sent");
} else{
for(var i=2; i<lr; i++){
var currentEmail = ss.getRange(i,26).getValue();
var currentClientName = ss.getRange(i,1).getValue();
var currentTeamName = ss.getRange(i,27).getValue();
var messageBody = sheet2Text.replace("{name}",currentTeamName);
var subjectLine = "notification on" + currentClientName + "process list", html;
MailApp.sendEmail(currentEmail, subjectLine, messageBody);
//26 is the column number that contains the emails in the google sheet
} //closing the for loop
} // closing the else loop
} // closing the function sendEmails
} // closing the onEdit function

Sending automatic email on specific day of the month based on day entered in a cell

I am trying to send an email from Google Apps Script on a specific day of the month based on the day that a user enters into a cell on the Sheet.
Currently I use a formula as below to send emails which sends to users based on cell values:
function sendChangeDetailsEmail() {
var sh = SpreadsheetApp.getActive().getSheetByName("BALANCE SHEET");
var data1 = sh.getRange("G2").getValues(); //USED AS DATA IN THE EMAIL BODY from values in the sheet
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G2");
var emailRange1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G1");
var emailAddress = emailRange.getValues();
var recipient = emailRange1.getValues();
var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
var subject = 'REMINDER - Amount Due';
MailApp.sendEmail(emailAddress, subject, message);
}
As the sheet will be used as a separate doc for each user, the user would enter the date in cell M3 on configuration for when they want the reminder to be sent, and they would only enter the date number of the month e.g. 25
Does anyone know of a way that I could do this please?
Send email once a month
function sendChangeDetailsEmail() {
var ss=SpreadsheetApp.getActive();
var sh = ss.getSheetByName("BALANCE SHEET");
var dt=new Date();
var today=dt.getDate();
var days=new Date(dt.getFullYear(),dt.getMonth()+1,0).getDate();//number of days in this month
var emailDay=sh.getRange('M3').getValue();
if(emailDay>0 && emailDay<=Days && emailDay==today) {
var data1 = sh.getRange("G2").getValue();
var emailRange = ss.getSheetByName("BALANCE SHEET").getRange("G2");
var emailRange1 = ss.getSheetByName("BALANCE SHEET").getRange("G1");
var emailAddress = emailRange.getValue();
var recipient = emailRange1.getValue();
var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
var subject = 'REMINDER - Amount Due';
MailApp.sendEmail(emailAddress, subject, message);
}
}
Run the next function just once and check Edit/Current Project Trigger to make sure that there is one and only one trigger created.
function createSendChangeDetailsEmail() {
ScriptApp.newTrigger('sendChangeDetailsEmail').timeBased().everyDays(1).atHour(6).create();
}
I have now got a script as below:
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Sheet1');
var rng = sh.getDataRange();
var val = rng.getDisplayValues();
var lr = rng.getLastRow();
var compare = sh.getRange('A9').getValue();
var match = false;
var body = "Hello, "+"\n\n"+"Please remember the below:";
for (var i = 1; i < lr; i++) {
if (val[i][2] == compare) {
var bodyVal = val[i][0];
body = body+"\n - "+bodyVal;
match = true;
Logger.log(body);
}
}
if(match) {
MailApp.sendEmail({
to: "mail#example.com",
subject: "Reminder",
body: body
});
}
}
I hope this helps someone who may be looking for the same thing :)

Updating different tab with a script from a pivot table????

I am new to coding scripts in google and come into a problem I can not work through and my script "mentor" is still not that experienced and can't figure it out either.
I am trying to update a different tab on my sheet from a pivot table when I use my script to send out bulked emails.
So the link below will bring you to the dummy sheet built off my real sheet. The 'PM' tab column L is what I am trying to update. It starts at 1 on all jobs. The emails are sent out by the Blue button on the next tab 'Follow up email' (this is just a pivot table so I can always adjust who is getting the emails easily). But I cant figure out how to have it update the 'PM' tab with the button at the same time as the emails go out.
Link to the open shared spreadsheet. Feel free to play around if you can help.
https://docs.google.com/spreadsheets/d/1_hipIj4suI2xMGUrZhMTBDvkQv9Y9O3JRNNQUpSeAP0/edit?usp=sharing
(only got the emails to send properly so far)
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var rows = sheet.getLastRow()
var dataRange = sheet.getRange(2, 1, rows-1, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[1]; // Second column
var message = 'Hello, we have submitted this job ' + row[2] + ' days Ago. ' + row[4] + ' \n\n' + ' -' + row[5];
var subject = row[0]; // First column
MailApp.sendEmail(emailAddress, subject, message);
}
}
I need the button to send out emails on the 'Follow up email' tab and at the same time "email counter" (column L) would get 1 added to it on the 'PM' Tab. This way I can keep track of how many times that job was emailed from the sheet.
Try this code:
function sendEmails() {
var pmSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PM");
var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Follow up email");
var startRow = 2; // First row of data to process
var rows = emailSheet.getLastRow()
var dataRange = emailSheet.getRange(2, 1, rows-1, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[1]; // Second column
var message = 'Hello, we have submitted this job ' + row[2] + ' days Ago. ' + row[4] + ' \n\n' + ' -' + row[5];
var subject = row[0]; // First column
MailApp.sendEmail(emailAddress, subject, message);
updatePM(pmSheet, emailAddress);
}
}
function updatePM(sheet, email){
var value;
var emails = sheet.getRange("G3:G" + sheet.getLastRow()).getValues();
for (var i = 0; i < emails.length; i++)
if (emails[i][0] == email){
value = sheet.getRange("K" + (i+3)).getValue() + 1
sheet.getRange("K" + (i+3)).setValue(value);
}
}
I changed the way you got the sheets just to be safe, then I just wrote a small function that gets called after the email is sent, which checks the list of emails in the PM sheet and then updates the value in the sent email column.

Need to sendNotification for multiple columns and sheets

In an attempt to automate some of my work, I am beginning to learn basics of google scripts.
I have a spreadsheet in which I want to send an email notification when data is input into one column or another. There are also two tabs within this spreadsheet in which I would like this to occur.
The current result from the script is an email on the second 'sendnotification' function.
Question: How do I get the script to consider both functions?
I know this code can be condensed by likely using an IF fucntion in a better way but I am at a loss.
For some context: This is used in a manufacturing operation. The production is done by an offsite company and when they enter quantity into column 10 on either sheet, I want it to send a group of people an email that I work with. Similarly, when the product quality testing is done I want to be able to input into Column 12 and it send the offsite company an email.
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get Active cell
var mycell = ss.getActiveSelection();
var cellcol = mycell.getColumn();
var cellrow = mycell.getRow();
//Define Notification Details
var recipients = "ryan.helms#company.com";
var subject = "Disc production was entered on the "+ss.getName();
var body = ss.getName() + " has been updated with an amount produced. Visit " + ss.getUrl() + " to view the quantities entered.";
//Check to see if column is A or B to trigger
if (cellcol == 10)
{
//Send the Email
MailApp.sendEmail(recipients, subject, body);
}
//End sendNotification
}
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get Active cell
var mycell = ss.getActiveSelection();
var cellcol = mycell.getColumn();
var cellrow = mycell.getRow();
//Define Notification Details
var recipients = "ryan.helms#company.com";
var subject = "A lot of disc has been RELEASED by XYZ Company";
var body = ss.getName() + " has been updated with a lot of disc that were released by XYZ Company. Visit " + ss.getUrl() + " to view this updated information.";
//Check to see if column is A or B to trigger
if (cellcol == 12)
{
//Send the Email
MailApp.sendEmail(recipients, subject, body);
}
//End sendNotification
}
You'll need to set up an onEdit installable trigger (if you haven't already) and assign it to the following function:
function onEditEmailSender(e) {
var sheetName = e.range.getSheet().getName();
if (sheetName === "tab1" || sheetName === "tab2") {
var col = e.range.getColumn();
if (col === 10)
//send col 10 email
else if (col === 12)
//send col 12 email
}
}
The onEdit trigger passes a parameter with all sorts of information, the most useful in your case being e.range. This Range object corresponds to the cell that was edited to trigger the onEdit event. You can use it to get the name of the sheet (what you call tab) and the column that was edited.
Using that information you can send the appropriate email. Good luck!