Google App Script not sending auto Email via Trigger - google-apps-script

I have been trying to send auto Email through Google App-script. There are two similar scripts but have two different
Email Text
Email Body
Subject
I have also set a trigger to send Auto Email on edit and the script is send the Email when there is "Different" value in Col"E". (Script name is 2nd_Email)
I just want that if "New Request" value is come in Col"E" then 1st_Email script should follow.
I have tried at my end but sometimes 1st_Email scripts works and sometimes 2nd_Email works.
I want both of them to work according to Col"E" values.
Please visit the sheet.
https://docs.google.com/spreadsheets/d/1Eu-c5CPj6XKQSAkSumuprA41-Cx_jvOuUPHr9Zg8KyQ/edit#gid=797418690

Keep the trigger only for the First_email function and add the second code to your first one as an alternative to your if condition.
function First_email() {
var INITIALline = 2;
var columnSEND = 5;
var STATUScolumn = 16;
var textCONDITION = "New Request";
var textCONDITION2 = "Different";
var textSENT = "Mail_Sent"
var tab = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var interval = tab.getRange(INITIALline,1,tab.getLastRow()-INITIALline+1,STATUScolumn);
var dice = interval.getValues();
var yousent = false;
var email,subject,message;
for (var i=0; i<dice.length; ++i) {
if((dice[i][columnSEND-1]==textCONDITION) && (dice[i][STATUScolumn-1]!=textSENT)){
var email = dice[i][9]
subject = dice[i][6]+" | New Request | "+dice[i][0];
var message = "<font size='3' face='Comfortaa'>Dear Different "+dice[i][6]+",<br/><br/>"+
"Thanks for New Request with us."+dice[i][0]+".<br/><br/>"+
"<i>Thanks & Regards</i><br/>"+
"<b> New Request </b>";
MailApp.sendEmail(email, subject, message,{ htmlBody: message});
tab.getRange(INITIALline+i,STATUScolumn).setValue(textSENT);
yousent = true;
SpreadsheetApp.flush();
}
else if((dice[i][columnSEND-1]==textCONDITION2) && (dice[i][STATUScolumn-1]!=textSENT)){
var email = dice[i][9]
subject = dice[i][6]+" | Different | "+dice[i][0];
var message = "<font size='3' face='Comfortaa'>Dear "+dice[i][6]+",<br/><br/>"+
"Thanks for Different with us."+dice[i][0]+".<br/><br/>"+
"<i>Thanks & Regards</i><br/>"+
"<b> Different </b>";
MailApp.sendEmail(email, subject, message,{ htmlBody: message});
tab.getRange(INITIALline+i,STATUScolumn).setValue(textSENT);
yousent = true;
SpreadsheetApp.flush();
}
}
}

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

How can I get and send to the last row submitted?

I've built a script that will get the issue with a form submission (D2) then output the text with the information in an email. Right now the Email address location (B2) and issue (D2) are hard coded. How can I work the code to get the email and issue from only the last row submitted?
function SendNot() {
// Fetch the Issue
var reasonRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TriggerSettings").getRange("D2");
var reason = reasonRange.getValue();
// Check for Issue
if (reason==="nogps"){
// Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'No GPS...';
var subject = 'Latest VDGL Entry...';
GmailApp.sendEmail(emailAddress, subject, message);
}
else if (reason==="nobarcode"){
// Fetch the email address
var emailRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'No Barcode...';
var subject = 'Latest VDGL Entry...';
GmailApp.sendEmail(emailAddress, subject, message);
}
}
You can calculate the last row with content using the following method:
sheet.getLastRow()
In your example you can calculate this as follows:
var d_size = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TriggerSettings").getLastRow();
var b_size = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getLastRow();
and then you can use d_size to grab the last row reason elements:
var reasonRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TriggerSettings").getRange("D"+d_size);
and b_size to grab the last row email elements:
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerInfo").getRange("B"+b_size);
You can also use a different syntax to get the desired range:
Instead of getRange("D"+d_size) -> getRange(d_size,4)
Instead of getRange("B"+b_size) -> getRange(b_size,2)
References:
Sheet.getLastRow()

Auto-direct emails to specific addresses on Google Form submit

This is my first post so apologies in advance if I am posting to the wrong place or asking a question that has been answered elsewhere - go easy on me!
In a nutshell, I have a Google Form and a connected Google Sheet. I need to automate it so that, when a new form is submitted, an email is sent to a specific colleague (the student's supervisor). I have had a good go myself but am now totally stuck!
I have created the form, linked it to a sheet, written the code, added the trigger and tested by submitting a form. Nothing happened! No error messages, just... nothing!
Any advice hugely appreciated. I am very new to this and still taking baby steps.
The code I have cobbled together (which is probably full of errors!) is as follows:
function wa132657(e) {
//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 = row.getValues();
// get the supervisor name from the form submission
var supervisor = response[0][1];
Logger.log("DEBUG: Supervisor = "+supervisor);// DEBUG
// get the emails list
var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SupEmails");
// 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 the supervisor is equal to SupervisorEmail
if (supervisor == emaildata[i][0]){
// there is a match
//Next, get the email address
var emailSupervisor = emaildata[i][1];
Logger.log("DEBUG: supervisor = "+emaildata[i][0]+", email address: "+emailSupervisor);// DEBUG
// Finally, send the Email.
var theirName = e.values[2];
var theirProgramme = e.values[3];
var theAbsenceReason = e.values[8];
var theAbsenceStart = e.values[5];
var theAbsenceEnd = e.values[6];
var subject = "Student Absence Report";
var message = "New Absence Report: " + theirName + " \n Programme: " + theirProgramme; + " \n\n
Reason for Absence: \n" + theAbsenceReason + " \n Start of Absence" + theAbsenceStart + "\n End of Absence:" + theAbsenceEnd;
MailApp.sendEmail(emailSupervisor, subject, message);
}
}
}

Sending HTML newsletter emails via google spreadsheet

I have a spreadsheet that updates daily. values in Italic are being updated daily, Bold values are static labels.
Date: 9/20/2019
Number of cars in parking lot: 105
Last entry: 09:21 AM
Last Check out: Mr.X
I have setup a script to send an email with the updates to the users via googlespreadsheet. But the email that users receive is a plain text like this:
Date:,9/20/2019,Number of cars in parking lot:,105,Last entry:,09:21 AM,Last Check out:,Mr.X,,,,,
How can I make this code to send more userfriendly email with a table or colorful fonts, etc similar to a daily newsletter?
So, given the requirement, this script would transform your sheet data into an HTML table and then send it as the message body over an email (you're free to further modify the CSS as required)
Assuming that your sheet looks something like this -
And that your desired output is something like this -
You could use the following code and make necessary changes as required -
var SheetID = "YourSheetIDGoesHere"; //replace with your Spreadsheet SheetID
var sheetName = "YourSheetNameGoesHere"; //replace with your Sheet Name
var sheet = SpreadsheetApp.openById(SheetID).getSheetByName(sheetName);
function sendUpdate() {
var range = sheet.getDataRange();
var values = range.getDisplayValues();
var weights = range.getFontWeights();
var rowDisplay = range.getLastRow();
var columnDisplay = range.getLastColumn();
var message = '';
message = message + "<table rules='all' border='3' style='border-color: #666;' cellpadding='5'>\n";
for (var i = 0; i < rowDisplay; i++ ) {
message = message + "<tr>\n";
for (var j = 0; j < columnDisplay; j++ ) {
message = message + "<td style='text-align: 'left'; font-weight: " + weights[i][j] + ";'>" + values[i][j] + "</td>\n";
} // ends the for loop for each column
message = message + "</tr>\n";
}
message = message + "</table>\n";
MailApp.sendEmail(
{
to: Session.getActiveUser().getEmail(), //this will send the email to whoever is running the script; replace it with the desired email IDs
subject: "Subject Goes Here",
htmlBody: message
}
);
}
Inspired by this article here.

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
}
}
}