Sending Autoreponse Email Script on Form Submit - google-apps-script

I've used a script in another spreadsheet that emails me whenever someone submits a form. It emails me with a few answers to important questions as well as a link to to view the full response on the spreadsheet.
Here is my original code that works:
function Outreach_FormMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[1];
var subject = e.values[1]+" completed a Report for "+e.values[3]
var dates = e.values[7];
var goalMet = e.values[9]
var goalFocus = e.values[10]
var hyperlink = "myawesomelink.com"
htmlBody = name+' just completed the O/R Report for these dates: '+dates+'<br><br>Form completed on: '+timestamp+'<br>Was the goal met? '+goalMet+'<br>What was the goal focus? '+goalFocus+
'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I wanted to use this code for a new form with different questions, so I edited the code to just correspond to the correct qeustions.
This is the code that doesn't work:
function Team_ApplicationMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[3];
var subject = e.values[1]+' filled out the Teams Application Form!' ;
var startdate = e.values[12];
var enddate = e.values[13]
var Focus = e.values[19]
var hyperlink="myawesomelink.com"
htmlBody = name+' from: '+e.values[1]+'just completed the Teams Application Form for these dates: '+startdate+' to '+enddate+'<br><br>Form completed on: '+timestamp+'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I've done several test emails and for some reason, this version of the script will not work. I am adding this script to a form that already has responses on the spreadsheet. Would that make a difference? Really not sure what I did wrong in transferring the code to a different spreadsheet.

Thanks for the comments guys. I actually realized the above code does work as is. I forgot that I setup a filter in Gmail that was sending the autoresponse email to a folder I didn't see instead of the inbox. No problem with the code, I just forgot to check the right place the email was sent to.

Related

Google Sheet - Send Email

I need my google sheet to send emails every time a condition becomes true.
In this case, every time value of C2 is lower than value of J2.
On the cell L2 there is the email address.
The code (found online and just edited)
function CheckPrice() {
var LastPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("C2");
var LastPrice = LastPriceRange.getValue();
var EntryLimitRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("J2");
var EntryLimit = LastPriceRange.getValue();
var StockNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("B2");
var StockName = LastPriceRange.getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("L2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'Ticker ' + StockName + ' has triggered the alert';
var subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
With this code I don't receive any error, but I don't even receive the email.
I granted permissions as requested when I run the script for the first time.
On L2 I put the same email address I granted permission (I send email to myself).
I did a try even putting a secondary email address I have.
Can you please show me what's wrong ?
Issues:
See the first lines of your code where you define LastPrice,
EntryLimit and StockName. All of them are coming from the same
range: LastPriceRange.
I also removed all the unnecessary calls in your script. There is no
need to call
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts") so
many times when you can just put it in a variable and use that
variable instead.
Also, you don't need to define unnecessary
variables. For example, you can get the value of a cell with one line:
sh.getRange("B2").getValue().
Solution:
function CheckPrice() {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts");
const LastPrice = sh.getRange("C2").getValue();
const EntryLimit = sh.getRange("J2").getValue();
const StockName = sh.getRange("B2").getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
const emailAddress = sh.getRange("L2").getValue();
// Send Alert Email.
const message = 'Ticker ' + StockName + ' has triggered the alert';
const subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
If you want an email to be sent when you edit a particular cell, then you need to transform the aforementioned solution to an onEdit(e) trigger. If you want a time basis trigger then you can just use the solution above directly.

GmailApp not sending emails to gmail account every time

I am using this code to send emails (composing email content getting text from the sheet named ranges:
//compose issue emails to student and admin
function composeIssueEmail() {
//student's name, last name and email
var email = ss.getRangeByName("CourseProgressEmail").getValue()
var name = ss.getRangeByName("CourseProgressName").getValue()
var lastName = ss.getRangeByName("CourseProgressStudentLastName").getValue()
var subj = ss.getRangeByName("SetUpIssueTitle").getValue()
var subject = subj.replace("*imya*", name)
var bodyText = ss.getRangeByName("SetUpIssueBody").getValue()
var body = bodyText.replace("*imya*", name)
var link = getChecksheetURL()
var text = body.replace("*link*", link)
//send email to student
var studentEmail = sendEmail(email, subject, text)
var adminEmail = "AGcourseSup#gmail.com"
var adminSubj = ss.getRangeByName("SetUpAdminIssueTitle").getValue()
var adminSubject = adminSubj.replace("*imya*", name)
var adminSubjectFinal = adminSubject.replace("*familia*", lastName)
var adminText = ss.getRangeByName("SetUpAdminIssueBody").getValue()
var adminTextReplace = adminText.replace("*imia*", name)
var adminBody = adminTextReplace.replace("*familia*", lastName)
var adminText = adminBody.replace("*link*", link)
//send email to admin
sendEmail(adminEmail, adminSubjectFinal, adminText)
}
//gets current checksheet URL
function getChecksheetURL() {
var Url = ss.getUrl()
var linkMiddle = "#gid="
var sheetID = sheet.getSheetId()
var shecksheetURL = Url + linkMiddle + sheetID
return shecksheetURL
}
//sends emails
function sendEmail(email, subject, body) {
GmailApp.sendEmail(email, subject, body)
}
Execution transcript:
[19-06-12 16:39:43:396 EEST] Execution succeeded [2.399 seconds total runtime]
It sends stably to the gmail account that is the same as spreadsheet's one.
But to another gmail account it sends about every other time.
Details:
This code is executed (I log the line after this code)
The emails are visible in my outbound box but not arriving to any of the boxes of the recepient gmail.
Not in spam etc.
I don't get any messages, error or bounce notifications.
I tried MailApp instead - it's even worse and sometimes doesn't send even to my own email.
I tried to change things in settings config, but didn't find anything to work.
I set up a filter "never send to spam" and "always star it" - didn't work.
I deleted a link from it so it has no link - didn't work.
What can be a solution?
I handled this issue. The issue is about anti-spam filters not about the code.
I gained more trust to the email account by adding "Reply To" option within GmailApp.sendEmail method. It magically solved the problem so each email reaches target now.

Trying to write paragraphs with Google Script in Automated email response

I am trying to make a simple paragraph where I can enter a few lines of text, but am not picking it up very easily. Can I switch it to html in the script or is there an easier way to write a template paragraph?
My current script looks like this where I am making an automated email response whenever someone fills out a form (conference registration). Currently, everything in my message section comes out as one block.
I would like to be able to have a few paragraphs in the email such as "Don't forget to mail payment to (Address)" and then the "registration" answer to list as its own line as well with text before it.
Also, I want to be able to display the Tuesday- Thursday answers in a bulleted list.
function myFunction(e){
var userName = e.values[2];
var userEmail = e.values[11];
var Registration = e.values[1];
var Tuesday = e.values[16];
var Wednesday = e.values[17];
var Thursday = e.values[18];
var Friday = e.values[19];
var subject = "Conference Registration";
var Message = "Thank you for Registering for the Conference," + userName + "You have following registration type: " + Registration;
var message = "You have registered for the following sessions: " + Tuesday + Wednesday + Thursday + Friday;
MailApp.sendEmail(userEmail, subject, message);
}
As mentioned in the other answer, you can create html content in an email message, below is a simple example of how to do that based on your question.
btw I added a script to simulate a form sending so it will be much easier to test (without needing to send hundreds of forms while you play with html tags)
About HTML tags, a Google search on these words will show you far more tips and tricks that I could ever do in this answer... enjoy !
note : in the example below I changed the e.values indexes to simplify my test code... don't forget to re-adapt !
Code :
function testMyFunction(){
var e = {};
e.values = ['test user Name','test user Email','test Registration',' event on Tuesday','event on Wednesday','party on Thursday','nothing on Friday'];
myFunction(e);
}
function myFunction(e){
var userName = e.values[0];
var userEmail = e.values[1];
var Registration = e.values[2];
var Tuesday = e.values[3];
var Wednesday = e.values[4];
var Thursday = e.values[5];
var Friday = e.values[6];
var subject = "Conference Registration";
var htmlMessage = "Thank you for Registering for the Conference," + userName + "<br>You have following registration type: <li>" + Registration;
htmlMessage+=Tuesday+'</li><li>'+Wednesday+'</li><li>'+ Thursday+'</li><li>'+Friday+'</li>';
Logger.log(htmlMessage);
MailApp.sendEmail(Session.getActiveUser().getEmail(), subject,'html content',{htmlBody : htmlMessage});
}
Result screen capture :
If you want to use html formatting in your body, when you are calling sendEmail do it like this:
MailApp.sendEmail({
to: userEmail,
subject: subject,
htmlBody: message
});
This will tell Gmail to interpret the message variable as HTML and not just raw text.

Google Form - not filled fields

I started to use a Google Form recently. I created:
The Google form with some questions,
Spreadsheet where the script would put the answers
An template that would be filled with the answers, converted to PDF and sent to the e-mail address.
Everything works perfectly IF all the Google Form fields had been filled.
If there is at least one field that was left empty - all the answers are put correctly to the spreadsheet but get totally misplaced in the template... (fragment of my code below)
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "myemail#myemail";
var project_name = e.values[1];
var owner = e.values[2];
var team_members = e.values[5];
var project_initiator = e.values[6];
var stakeholders = e.values[7];
var deadline = e.values[3];
var related_projects = e.values[8];
var deliverables = e.values[4];
var project_summary = e.values[9];
var contribution = e.values[10];
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyProjectName', project_name);
copyBody.replaceText('keyOwner', owner);
copyBody.replaceText('keyTeamMembers', team_members);
copyBody.replaceText('keyProjectInitiator', project_initiator);
copyBody.replaceText('keyStakeholders', stakeholders);
copyBody.replaceText('keyDeadline', deadline);
copyBody.replaceText('keyRelatedProjects', related_projects);
copyBody.replaceText('keyProjectSummary', project_summary);
copyBody.replaceText('keyContribution', contribution);
And a fragment of the template:
http://zapodaj.net/images/ce3895cc6614f.png
Thank you for any advises, answers..
The easiest way to fix this issue would be to make all of the questions from your form a required questions.
That way, the user will be unable to leave an answer blank and your template will auto-populate in the correct order.
Hope that helps

Google Forms Complex Email Send on Form Submit with Script

I have this right now as a script to send an email to myself as a test showing that there is a new application submitted, but I am looking to have a full-fledged email sent to our HR department giving the name of every field following by a : and a space then what their answer was. I know you can do this and have found a script that I tried to get to work, but it kept failing and the developer was no help in trying to help me fix it. I really would love to get this done for my HR department so that we can move on from creating a new application. Here is my code so far, I removed my email for privacy issues:
function sendFormByEmail(e){
var email = "emailgoeshere";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please go to the spreadsheet for more details.";
MailApp.sendEmail(email, subject, message);
}
Thanks again!
Or you could try this very simple one :(read carefully comments in the script)
function sendFormByEmail(){
var email = "email adress comes here";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please find the details below :";
var row = SpreadsheetApp.getActiveSpreadsheet().getLastRow();// assuming data is on the last row of the spreadsheet
var messagebody=createmessage(row);
MailApp.sendEmail(email, subject, message+messagebody);
}
//
function createmessage(row){
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastCol = ss.getLastColumn();
var LF= "\r\n"
var body = LF
var headers = sh.getRange(1,1,1,lastCol).getValues();
var data = sh.getRange(row,1,1,lastCol).getValues();
for(nn=0;nn<headers[0].length;++nn){
body+=headers[0][nn]+" : "+data[0][nn]+LF
}
Logger.log(body)
return body
}
//
//eof
As mentionned, data coming from the form must be on last row of data in the sheet and there must be some data to check how it works otherwhise answers=questions.
I've developed a script that might help you, it's called FormEmailer. You can find it in the Script Gallery or grab the code on its site.