Google Forms Complex Email Send on Form Submit with Script - google-apps-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.

Related

Google Docs script editor trying to autogenerate an email from an autogenerated document

Everything I've found about this topic includes having a google sheet populate a google doc which then sends an email. I personally have pasted some code I found around the web into script editor of a doc. Now, upon opening a doc, the user is prompted to answer question boxes. the answers autopopulate a new document that is created. The script then calls for an email to be sent out.
So far, I have the prompts correct, the new document is created, with the correctly filled-in information from the prompt boxes. I have also gotten it to send an email to 1 address, which is all it is supposed to do. The subject line of the email is also correct. The problem is I want the new Google document that is created in the script to be the body of the email, and I just cannot figure out how to make that happen.
This is the code I have in script editor. I have tried numerous things in the last line to make the body of the new document populate the email body, with no luck. Can someone tell me the programming language for how to make this work please?
function myFunction() {
// Display a dialog box for each field you need information for.
var ui = DocumentApp.getUi();
//var response = ui.prompt('Enter Name', 'Enter sales person's name', ui.ButtonSet.OK);
var shiftResponse = ui.prompt('Enter shift, i.e. 7-3 or 3-11');
var peersResponse = ui.prompt('Enter peers on shift');
var participantsResponse = ui.prompt('Enter names of face to face encounters');
var phonelogResponse = ui.prompt('Enter names of people we called on phone log');
var filescreatedResponse = ui.prompt('Enter names of people we created files for');
var notesResponse = ui.prompt('Enter any notes about shift');
var cleanResponse = ui.prompt('Was Crisis Center Cleaned? Enter yes or no');
var authorResponse = ui.prompt('Enter your name');
var date = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
//Make a copy of the template file
var documentId = DriveApp.getFileById('1lXTJPvwlJrXkRJ807daFsFbfaiC_wl7EAQ4giixLeEc').makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName(date + " " + shiftResponse.getResponseText() + ' Shift Report');
//Get the document body as a variable
var body = DocumentApp.openById(documentId).getBody();
//Insert the entries into the document
body.replaceText('##date##', date);
body.replaceText('##shift##', shiftResponse.getResponseText());
body.replaceText('##peers##', peersResponse.getResponseText());
body.replaceText('##participants##', participantsResponse.getResponseText());
body.replaceText('##phonelog##', phonelogResponse.getResponseText());
body.replaceText('##filescreated##', filescreatedResponse.getResponseText());
body.replaceText('##notes##', notesResponse.getResponseText());
body.replaceText('##clean##', cleanResponse.getResponseText());
body.replaceText('##author##', authorResponse.getResponseText());
MailApp.sendEmail("jason.chrystal#voicesofhopececilmd.org", "Shift Report", body);
}
As it reads in the documentation:
The replaceText methods expects a regex pattern value as the first parameter:
https://developers.google.com/apps-script/reference/document/body#replacetextsearchpattern,-replacement
Also the last parameter of the MailApp.sendMail parameter expects a string and you are giving it a body class object.
Change your first parameter to a correct matching regex pattern and your code will work just fine.
body.replaceText(/^##date##$/, date);
body.replaceText(/^##shift##$/, shiftResponse.getResponseText());
body.replaceText(/^##peers##$/, peersResponse.getResponseText());
etc...
-- regex not tested.
If you are not comfortable with regular expressions you can use body.setText() as an alternative like so:
var oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##date##', date));
oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##shift##', shiftResponse.getResponseText()));
oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##peers##', peersResponse.getResponseText()));
etc...
// And then the last lines:
var newBody = body.getText();
MailApp.sendEmail("jason.chrystal#voicesofhopececilmd.org", "Shift Report", newBody);

Paste image in email before sending, google app scripting

Google App scripts noob here. I am trying to send email from google sheets and I have a working code. However, the challenge I have unaddressed is to paste an image in the email before sending it. The image that needs to be pasted is copied from the snipping tool. In Microsoft Outlook, I have used .Show function to preview the email and paste the image but I am unable to achieve the same in google app scripting. The image is different every time an email is sent and saving the image to a drive location defeats the automation effort so the preferred option is to paste the image before its sent. I would appreciate any suggestions and recommendations to make this happen. I am sure there is a way to do this and I am at the right place to find that way.
function SendNote() {
var active_range = SpreadsheetApp.getActiveSpreadsheet().getActiveRange();
var env_type = SpreadsheetApp.getActiveSheet().getRange(active_range.getRowIndex(), 1).getValue();
var count = SpreadsheetApp.getActiveSheet().getRange(active_range.getRowIndex(), 4).getValue();
var mail_type = SpreadsheetApp.getActiveSheet().getRange(active_range.getRowIndex(), 13).getValue();
// Check totals sales
if (mail_type = 'Kick_Off')
{
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Email.
var message = 'This is my message ' + env_type; // Second column
var subject = 'This is the subject';
MailApp.sendEmail('myhandle#mymail.com', subject, message);
}
}

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 Apps Script: create a pdf by editing response to google form

I'm hoping that someone can help me, What i want to do is to make a Google form create a new document and send that pdf via email when the form is edited.
I understand that when you edit a form the script inside a spreadsheet does not run, So i have put the script into a form and that is where i am having problems. I can not get the script to read the values that are been resubmitted on the form, it just keeps on coming up as "undefined" on the return
This is the script that i have got so far.
function Test(e) {
var form = FormApp.openById('****Form Key****'); //Enter Form ID here
var docTemplate = "***doc to be used***";
var docName = "***Name of document***";
var formResponse = form.getResponses();
var one = e.response; //I have tried e.value but does not pull through
var two = e.response; // Column 2
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('one', one);
copyBody.replaceText('two', two);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
//Sends the email
var email_Address = "***Email Address***"
var subject = "***Subject";
var body = "**Body***";
MailApp.sendEmail(email_Address, subject, body, {attachments: pdf});
}}
Any help will be greatly appreciated as i have been stuck on this for a while. thank you.
In a Form Response Trigger function, the event is an instance of Class FormResponse. Because of that, you don't need to open the form, or get responses... you've just had one handed to you, which you access via e.response. (See Form Response Events in Understanding Events.)
// Handle form response event
// This function must be a Form Response Trigger, attached to
// a Form (not a Spreadsheet).
function rightTest( e ) {
var formResponses = e.response.getItemResponses(); // array of responses
var one = formResponses[0];
var two = formResponses[1];
...
}
As of April 2015, DocsList is not supported, simply replace DocsList. with DriveApp. How to update DocsList to DriveApp in my code

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.