Trying to write paragraphs with Google Script in Automated email response - google-apps-script

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.

Related

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

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.

Google Scripting Assistance

Im trying to setup a form that will email me peoples responses.
This is the current script:
function nl2br_(input_string){
return input_string.replace(/(\r\n|\r|\n)/g,'<br />');
}
function contactUsMailer(e) {
// This script e-mails the contents of a form to a given recipient
// The form must have three fields in the order of: name; e-mail address; and message
// You must change the recipient variable below to your e-mail address
try {
var recipient = 'myemail#hotmail.com';
var timestamp = e.values[0];
var username = e.values[1];
var option = e.values[2];
var details = e.values[3];
var body = username+' sent the following message: '+option ;
var bodyHTML = '\
<p>'+username+' '+option+' below are the details </p>\
<blockquote>'+nl2br_(details)+'</blockquote>\
<p>Sent by the Steegle.com Contact Us Form Google Apps Script</p>';
var advancedArgs = {htmlBody:bodyHTML , replyTo:username};
MailApp.sendEmail(recipient, "Contact Us Form", body, advancedArgs);
} catch(e){
MailApp.sendEmail(recipient, "Error - Contact Us Form", e.message);
}
}
This is how it looks when I get an email:
var timestamp - not important ignore it
var username - their username
var option - this is the "issue"
var details - detail of problem
I would really like it to look something like this:
Username: "username here"
Issue: "issue here"
Details:
"wall of text for details here"
I've been at this for over an hour and a half and I can't get it to look anything remotely like what what is shown above :/
I had a similar situation and this is how I solved it.
I created a HTML Output with a table inside and then Sent this as My Email Body.
var log = HtmlService.createHtmlOutput()
log.append('<body><table border="1">');
log.append('<tr></td> Username: </td><td>' + usernameVAR +'</td></tr>');
log.append('<tr></td> ISSUE </td><td>' + issueVAR +'</td></tr>');
log.append('<tr></td> DETAILS </td><td>' + detailsVAR +'</td></tr>');
log.append('</table></body>');
var htmlContent = log.getContent();
MailApp.sendEmail(YOUR EMAIL GOES HERE ,"TITLE OF EMAIL", "SUBJECT LINE",{htmlBody:htmlContent} ) //Text as HTML
Good Luck!

Sending Autoreponse Email Script on Form Submit

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.

How do I create a form letter where some text is not printed if a field on a Google form is left blank

My company recently switched to Google Apps and I am trying to covert Word and Excel docs to Google Docs. I am completely new to Google App Script and am stuck. I have been searching for a few days a have not found what I am looking for.
I have a Google form that is emailed to a sales person. After it is completed the Google spreadsheet is updated and then sends a form letter to the sales person summarizing their input. Some of the fields on the form are optional. How do I create a template that does not include some of the form letter text if the question was left unanswered?
For example, one of the optional fields is for a customer website address, if the customer does not have a website I don’t want the words website to show up on the form.
If anyone has any “For Dummies” instructions on how to do this I would really appreciate it.
Thanks.
Here is what I have so far:
// Business Review Report
// Get template from Google Docs and name it
var docTemplate = "1gRk2irahyW2Sf4pQMTDykXlMQqYgbe1Ba1vkh20KDYo";
var docName = "Business Review";
// When Form Gets submitted
function onFormSubmit (e) {
//Get information from form and set as variables
var variablename = "static entry or form value"
var email_address = e.values[1];
var Business_Name = e.values[2];
var Business_Address = e.values[3];
var Phone_Number = e.values[4]
var Email_address = e.values[5];
var Website = e.values[6];
var Participants = e.values[7];
var Agenda = e.values[8];
var Updates_and_Progress1 = e.values[9];
var Updates_and_Progress2 = e.values[10];
var Updates_and_Progress3 = e.values[11];
var Current_Issues1 = e.values[12];
var Current_Issues2 = e.values[13];
var Current_Issues3 = e.values[14];
var Next_Steps = e.values[15];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+ Business_Name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyBusinessName', Business_Name);
copyBody.replaceText('keyBusinessAddress', Business_Address);
copyBody.replaceText('keyPhoneNumber', Phone_Number);
copyBody.replaceText('keyEmailaddress', email_address);
copyBody.replaceText('keywebsite', Website);
copyBody.replaceText('keyParticipants', Participants);
copyBody.replaceText('keyAgenda', Agenda);
copyBody.replaceText('keyUpdatesAndProjects1', Updates_and_Progress1);
copyBody.replaceText('keyUpdatesAndProjects2', Updates_and_Progress2);
copyBody.replaceText('keyUpdatesAndProjects3', Updates_and_Progress3);
copyBody.replaceText('keyCurrentIssues1',Current_Issues1);
copyBody.replaceText('keyCurrentIssues2', Current_Issues2);
copyBody.replaceText('keyCurrentIssues3', Current_Issues3);
copyBody.replaceText('keyNextSteps', Next_Steps);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Business Review";
var body = "Business Review for " + Business_Name + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}
It works, but the resulting PDF also includes text for the unfilled fields like CurrentIssues2.
I am not sure if I am explaining this clearly so please respond with any questions and I will try to be more clear.
Thanks again,
Lisa
Your form questions apparently have default values that you don't want in your form letter. You can check for those defaults and replace them with something more suitable, such as a blank string.
...
// If website question was not answered, leave blank
var Website = e.values[6];
if (Website == 'website') Website = '';
...
This alternative uses the Ternary or Conditional Operation, and is more compact:
...
// If website question was not answered, leave blank
var Website = (e.values[6] == 'website') ? '' : e.values[6];
...