Google Forms Script Editor to send emails based on answer - google-apps-script

I use a Google Form to track employee hours and jobs completed for a mechanical services small business. The guys want to be able to get an email of their responses to track their own hours and ensure they put everything in correctly. I don't want them to have to enter their email every time or log in - they complete this on their phones and want to keep it as simple and less repetitive as possible.
I've looked on a lot of places around here and have (what I think) is the basis of a good code in Google Script Editor. I had it working to send an automated email, but when I added the information in the message it didn't work. I used some other examples out there and tried to put a few together to make it work. I'd appreciate any help critiquing this code and helping me figure out why it isn't working. I'm new to this and can't seem to figure it out. Thanks.
function EmailTimeSheetCMS(e){
var name = e.values [1];
var ReplyEmail = "__________#yahoo.com"
var Email1 = "__________#gmail.com"
var WorkOrder = e.values[2];
var date = e.values[3];
var location = e.values[4];
var jobdescription = e.values[5];
var notes = e.values[6];
var vendors = e.values[7];
var starttime = e.values[8];
var endtime = e.values[9];
var otherworkers = e.values[10]
var status = e.values [11];
var reghrs = e.values[12];
var othrs = e.values[13];
var tools = e.values[15];
var message = "You entered the following information" + "\nDate " + date + "\nWork Order # " + WorkOrder + "\nLocation " + location + "\nStart Time" + starttime + "\nEnd Time " + endtime + "\nRegular Hours worked" + reghrs + "\nOvertime Hours " + othrs + "\nJob Description " + jobdescription + "\nNotes " + notes + "\nVendors and Invoices " + vendors + "\nOther Workers Present " + otherworkers + "\nTools Used " + tools + "\nJob Status " + status ;
if(name = 'Bill')
{MailApp.sendEmail(Email1, ReplyEmail, "CMS Time Submission - Bill", message) }
else if(name = 'Scott')
{MailApp.sendEmail(ReplyEmail, ReplyEmail, "CMS Time Submission - Scott", message)
} }

On a first glance I see a potential flaw.
In the if condition i.e when you say
if (name = 'Bill')
it assigns 'Bill' to the variable name.
could you try writing it as
if(name == 'Bill')
and see if it works.
And when posting a question next time, it is always a good practice to enter the error message you get. Or at least the 'Execution transcript' available under the View in menu bar

Related

Google Apps Script to send email notification, if the email from an expected sender is not received every 1 hour

I have managed to get email notification alert if I have not received an expected email in past XX day.
By following the guidelines given in - http://baumbach.com/google-script/
It is working as expected.
Here is the javascript code-
function SearchEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
// "in:all " searches trash and spam email folders. Remove "in:all " + to only search all mail and inbox
var gsearch = "in:all " + "from:(" + data[i][1] + ") to:(" + data[i][2] + ") subject:(" + data[i][3] + ") newer_than:" + data[i][4] + "d";
var threads = GmailApp.search(gsearch, 0, 1);
if (threads.length == 0) {
var emailSubject = "No email in " + data[i][4] + " days: - " + data[i][5];
var emailText = "Note: " + data[i][5] + "\r\n\r\nSearch was: " + gsearch;
var emailTo = data[i][0];
MailApp.sendEmail(emailTo, emailSubject, emailText);
}
}
}
But, What I want is, to get email notification alert if I have not received an expected email in past 1 Hour and not days.
Can anyone tell me how to do this and where should I change the code??
Thanks a lot in advance.
EDIT
In the guide from the link you provided and in your code, the date used to query the messages from Gmail comes from the linked spreadsheet you have, so this part would be set by you.
To query the message the code uses the gsearch variable which is formatted by the q parameter guidelines using the Gmail search operators and inserting data in the query from the data variable which is obtained from using the getDataRange and getValues methods to your sheets. For what I see in the search operators, there's no option to query the messages by time, the minimum is 1 day.
Also, they explain they set up a time driven trigger to execute the SearchEmail function once a day. For this part you can use the everyHours method to create a trigger to execute the function once every hour. Run the below function once in order to create the trigger:
function createTimeTriger1hour() {
ScriptApp.newTrigger("SearchEmail")
.timeBased()
.everyHours(1)
.create();
}

I would like to populate an email message with the contents of a specific, static, cell in sheets

I am sending a confirmation email when someone signs up for an appointment on a Google form. I would like to have the email message be populated with the contents of a specific cell. This means I would be able to type an email message into cell A2 and when someone fills out a form, it will send that message to them as the confirmation email.
I have two different email messages I am using, confirmation email and reminder email. I would like both codes to populate the same message.
function confirmationEmail(e) {
var userName = e.values[2];
var userEmail = e.values[3] + ";user#gmail.com";
var date = e.values[4];
var studentName = e.values[1];
var body1 = "Hello " + userName + ",";
var body2 = studentName + " has been registered for a physical at High School for the following date/time:";
var body3 = "Please park in the large student parking lot on the east side of the High School.";
var body4 = "Thanks!";
var signature = "Name" + "\n" + "High School" + "\n" + "user#gmail.com" + "\n" + "***-***-****";
var file1 = DriveApp.getFilebyId("1WDxic1meHzEGSjybJ2SS1h2MqGAhIAK4");
var file2 = DriveApp.getFilebyId("1v4GQAP8PkTPQRPoYIdsEOMBr2ZvRO1eocsqixyZ42gA");
GmailApp.sendEmail(userEmail,
"Registration",
body1 + "\n\n" + body2 +"\n\n" + date + "\n\n" + body3 + "\n\n" + body4 + "\n\n" + signature,
{attachments:[file1, file2]})
}
This code works perfectly already, however, I have some co-workers even less savvy than I. It would work best if they could just fill in the cell with the contents of the message to be able to send this out. So ideally, "body3" would be written into a cell within sheets and populated into the email.
So I guess you would want something like this:
var body3 = SpreadsheetApp.getActiveSheet().getRange('A2').getValue();
You should probably include some conditional statements in the code to prevent the sending of the email in the event that cell 'A2' is blank and include an alert to inform the user that it needs to be filled in.
Perhaps something like this:
if(body1 && body2 && body3){
//send email
}else{
SpreadsheetApp.getUi().alert('Invalid or Missing Content');
}
Truthy

Google app script - how to count number of google form response

It is my first time writing google app script and I am desperately need help.
The purpose is to set up a workshop sign up form. Based on how many people already signed up, an email is sent out to inform if sign up was successful, or was put in the wait list.
I copied code from a tutorial. But need help to get the count of form responses. Here is how it looks like now:
function onFormSubmit(e) {
var timestamp = e.values[0];
var yourName = e.values[1];
var toAddress = e.values[2];
var subject = "Workshop Confirmation";
var emailBody = "Thank you for your submitted on " + timestamp
var num_response = COUNT_NUMBER_OF_RESPONSE // <-- need help here
var LIMIT = 15
if (num_response <= LIMIT) {
emailBody = emailBody + "\n\nYou are enrolled in the workshop";
}
else {
var wait = num_response - LIMIT
emailBody = emailBody + "\n\nThe workshop is full. You are #" + wait + " in the waiting list"
}
emailBody = emailBody + "\n\nThe details you entered were as follows: " +
"\nYour Name: " + yourName +
"\nYour Email: " + toAddress ;
MailApp.sendEmail(toAddress, subject,
emailBody, optAdvancedArgs);
}
I have no clue how to find right answer in the google app document. Any help would be greatly appreciated!
How about the composite function
FormApp.getActiveForm().getResponses().length
no need to go around looking for the spreadsheet (since in my experience, the spreadsheet is not always up to date, whereas the form is)
From what I see in the tutorial, this script is embedded in a spreadsheet so the easiest would be to count the number of rows and substract 1 because of the headers...
There is a method for that : getLastRow(), the doc refered in this link should give you enough information to write the few lines of code you need...
test :
function xx(){
var lr = SpreadsheetApp.getActiveSheet().getLastRow()-1;
Logger.log(lr);
}
Script on form (not spreadsheet)
function onFormSubmit(e) {
var num_response = FormApp.getActiveForm().getResponses().length
var LIMIT = 20 //or whatever
if (num_response < LIMIT) {
}
else {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(false);
}
}

Google script - Can't attach a PNG file from Google Drive to form email

I've setup a trigger with the following code to send out an email everytime an employee submits a request. What this basically does is send out a brochure (in PNG format and stored in Google Drive). Somehow, the code does not work. Spent almost the entire day scouring the net for answers, but none helped. I tried the DriveApp.getFileByID method and it worked, but that was just for one file. The attachment depends on the product that the employee selects on the Google form, and that is dynamic.
Any help is much appreciated. Thanks!
function SendBrochure(e) {
try {
var email = e.values[1];
var subject = "ABC Co - Information you requested";
var msgcc = "test#gmail.com";
var aliases = GmailApp.getAliases();
var cxnm = e.values[2] + " " + e.values[3] + " " + e.values[4];
var msgl1 = "Greetings from ABC Co, " + cxnm + ".";
var emailText = "<b>Greetings from ABC Co, " + cxnm + ". </b> <p>With reference to your conversation
with us and your request for information, please find attached herein the same.</p> <p> Should you
require further assistance, please contact the undersigned, or refer to the brochure for pertinent
site contact details.</p> <p>We appreciate your interest and look forward to your visit soon.</p>
<p> Thanks and regards, <br><b>ABC Co</b><br>Tel: +1 202 555 1212<br>Web:
www.abc.com </p>";
var brochurename = e.values[5]; //gets file name from form (already filled in - for e.g f_1.png)
var brochure1 = DriveApp.getFilesByName(brochurename);
GmailApp.sendEmail(email, subject, msgl1, {
name: 'ABC Co',
attachments: [brochure1.next()],
htmlBody: emailText,
from: aliases[1]
});
GmailApp.sendEmail(msgcc, "Email sent!", "Your email request to " + email + " has been completed successfully at " + e.values[0], {
'from': aliases[1]
});
} catch (e) {
Logger.log(e.toString());
}
}
try getting the image as a blob with the right mime type, see [doc here][1],
in your code it would become :
...
attachments: [brochure1.next().getAs('image/png')],
...
PS : didn't have the opportunity to test this, please let us know it it does work. [1]: https://developers.google.com/apps-script/reference/drive/file?hl=fr-FR#getAs%28String%29
EDIT : here is a new version of your code that works, just change the image file names to suit your case.
I wrote a test function to be able to test without form submission.
function test(){
var par = {};
par['values']={};
par.values[0]=new Date();
par.values[1]='xxxxxxx#gmail.com';
par.values[2]='xxxxx';
par.values[3]='yyyyy';
par.values[4]='zzzzz';
par.values[5]='LOGO.jpg';// just for test I took a file I had in my drive
SendBrochure(par);
}
function SendBrochure(e) {
Logger.clear();
var email = e.values[1];
var subject = "ABC Co - Information you requested";
var msgcc = "yyyyyyyy#gmail.com";
var aliases = GmailApp.getAliases();
var cxnm = e.values[2] + " " + e.values[3] + " " + e.values[4];
var msgl1 = "Greetings from ABC Co, " + cxnm + ".";
var emailText = "<b>Greetings from ABC Co, " + cxnm + ". </b> <p>With reference to your conversation "+
"with us and your request for information, please find attached herein the same.</p> <p> Should you "+
"require further assistance, please contact the undersigned, or refer to the brochure for pertinent "+
"site contact details.</p> <p>We appreciate your interest and look forward to your visit soon.</p>"+
"<p> Thanks and regards, <br><b>ABC Co</b><br>Tel: +1 202 555 1212<br>Web: www.abc.com </p>";
var brochurename = e.values[5]; //gets file name from form (already filled in - for e.g f_1.png)
var brochure = false;
Logger.log('brochurename = '+brochurename)
var brochure1 = DriveApp.getFilesByName(brochurename);
if(brochure1.hasNext()){
var brochure = brochure1.next().getBlob();// get the blob
Logger.log('brochure name = '+brochure.getName())
}else{
Logger.log("didn't find a file with name = "+brochurename)
}
Logger.log('email data = '+email+' '+subject+' '+ msgl1)
if(brochure){
GmailApp.sendEmail(email, subject, msgl1,{attachments:[brochure], htmlBody:emailText});
GmailApp.sendEmail(msgcc, "Email sent!", "Your email request to " + email + " has been completed successfully at " + e.values[0])
}
GmailApp.sendEmail(msgcc, "Email not sent!", "Your email request to " + email + " has not been sent because of an invalid attachment\nSee Log below : \n\n"+Logger.getLog());
}

Set Value on a DIFFERENT Sheet in Google Apps Script

I want to do a variation on the "Sending emails from a Spreadsheet" tutorial on the Google Developers page.
I want to do exactly what they walk me through EXCEPT that when it comes to marking the cell in each row every time the e-mail is sent, I want to mark that on a SEPARATE sheet.
So, on the sheet "NeedReminders", my script finds the e-mail addresses of members to whom the e-mail should be sent in column A (which then becomes variable "emailAddress"). It sends the e-mail to that address.
THEN--and here's where I need help--I want the script to go to the "Master" sheet, find the row where emailAddress is in column X, and--in that same row--set the value of column BT.
Shouldn't be difficult. I just don't necessarily know how to do the "find the row where columm X equals emailAddress and set value of BT to today's date" part.
Who can help? Thanks in advance!
Here's my code so far (I'm always embarrassed to show my code because I'm sure it's terrible juvenile, so be gentle, please!):
function sendDuesReminder() {
var sheet = SpreadsheetApp.openById('___').getSheetByName('NeedReminders');
var startRow = 4; // There are a bunch of headers and other nonsense.
var valueSheet = SpreadsheetApp.openById('___').getSheetByName('Master');
// Determine how many rows to process
var rowRange = sheet.getRange(3,4); // On my sheet, cell D3 counts how many members are on the list of people who need a reminder e-mail.
var rowData = rowRange.getValue();
// End Determine how many rows to process
// Send e-mail
var dataRange = sheet.getRange(startRow, 1, rowData, 2);
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
// var emailAddress = row[0]; //Column A: E-mail Address
var name = row[1]; //Column B: First Name
var subject = "Reminder About Dues for Newcomers & Neighbors";
MailApp.sendEmail("matt#twodoebs.com", subject, "Hi, " + name + ". It's been some time since we received your online registration for Newcomers & Neighbors. But we don't seem to have received your dues payment, yet. So we wanted to drop you a quick line and remind you about it." + "\n\n" + "If you think we should have received your payment by now or there's some kind of a mistake, please let us know by responding to this message." + "\n\n" + "Otherwise, please send a check for __ made payable to ___ to:" + "\n\n" + "___" + "\n" + "___" + "\n" + "___" + "\n" + "___" + "\n\n" + "Thanks! Please don't hesitate to reach out if you have any questions." + "\n" + "___" + "\n" + "___" + "\n\n" + "Best wishes," + "\n\n" + "Kati" + "\n" + "Membership Director",
{name:"___"});
// End Send E-Mail
// Set that an a-(Experimental)
var valueRange = valueSheet.getRange // Here's where I kind of break down . . . I need *something* here that searches the sheet for emailAddress
setValue(today()) //I'm also not sure that this is the right way to set the value as today's date
SpreadsheetApp.flush();
// End Set value
}
Browser.msgBox("OK. Reminder messages have been sent. doebtown rocks the house!")
}
If you're still struggling, try this:
var emails = valueSheet.getRange('X:X').getValues();
var targetRange = valueSheet.getRange('BT:BT');
var dates = targetRange.getValues();
for (var j=0; j<emails.length; ++j) {
if (emails[j][0] == emailAddress) {
dates[j][0] = new Date();
break;
}
}
targetRange.setValues(dates);