Google Apps Script — Automatically Email and Share - google-apps-script

I am attempting to write a small Google Apps script that will send a confirmation email and automatically share a folder with a logged-in user after they complete a form. Here is the script:
function formSubmitReply(e) {
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: "Keuka College Brand Download Center",
htmlBody:
"<p>Thank you for requesting access to the Keuka College Brand Download Center. Your access has been approved.</p>" +
"<p>You may access the download center by <a href='https://drive.google.com/a/keuka.edu/folderview?id=0B856ZeGoaGT_MG5BMEtEVGwzYkk&usp=sharing'>using this link,</a> " +
"visiting <a href='http://brand.keuka.edu'>Keuka College Brand Central,</a> or through your Google Drive.</p><p>Please contact the Office of Marketing and Communications " +
"with any questions you may have.</p>",
name: "Keuka College",
replyTo: "marketing#keuka.edu"
});
var folder = DocsList.getFolder('Brand Download Center');
folder.addViewer(Session.getActiveUser());
}​
This seems to be working, except it keeps emailing it to me -- not the user who is completing the form. I am not sure if it is sharing correctly.
Could someone provide some insight? This is my first time working with Google Apps script.

Session.getActiveUser() is the user that uses the form editor and the user that created the trigger that calls this function.
What you want us the user that filled the form.
Look at the documentation here to see how you can retrieve that value. Note that it will only be available if you are in a domain.
EDIT (sorry for the delay)
Here is a sample code to show how to get the form respondent in formApp (works only in GAFE or GA Business)
It will send you a mail with the name of the last form submitter (don't forget to create an installable onEdit trigger to test this).
function onSubmit(){
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
var lastResponse = formResponses[formResponses.length-1];
var user = lastResponse.getRespondentEmail()
var userString = 'user = '+user;
MailApp.sendEmail(Session.getActiveUser().getEmail(),'form submission report',userString);
}

Related

Filling Google Forms with Google Sheets

I have an HTML form which saves its responses to a Google Sheet. The form contains the following fields:
Name:
Email:
Subject:
Message:
Now, what I want is I want to automate sending a thank you email to a recipient as soon as he/she fills the form to the address mentioned in the "Email" field. I don't want to use Google Forms as the backend as it is hard to bypass the "Response Recorded" Confirmation page. Also, avoiding PHP would be better for me!
Is there a way to send these e-mails automatically? The format of the email is as follows:
From: <my email address>
To: <email address from the "Email" field in the spreadsheet>
Subject: Re: Submission Received
Hey <name from the "Name" field in the spreadsheet>!
Body of the mail
If there is a way to bypass the confirmation page of Google Forms, please let me know! That would also do!
If you have the data in google sheets, then you can handle your automation there. I setup this sample file that you could probably base your data set on.
From there I attached the below script to the spreadsheet. You would then need to set a trigger to execute this script on a somewhat regular frequency (5 minutes? 1 minute?). I think it should accomplish what you are going for. There's a check built in to ensure that partial data is not sent.
const ss = SpreadsheetApp.getActiveSheet();
const sentMessageColumn = ss.getRange("E:E").getColumn();
function regularProcedure(){
var aCell = ss.getRange(ss.getLastRow(),sentMessageColumn)
while(aCell.isBlank()){
var eRow = aCell.getRow();
if(!(ss.getRange(eRow,2).isBlank() ||
ss.getRange(eRow,3).isBlank() ||
ss.getRange(eRow,4).isBlank()))
{
var newMail = GmailApp.createDraft(
ss.getRange(eRow,2).getValue(),
ss.getRange(eRow,3).getValue(),
ss.getRange(eRow,4).getValue());
newMail.send();
aCell.setValue(true);
}
aCell=aCell.offset(-1,0);
}
}

Allow only selected account to submit a Google Form

Is there a way (Apps Script maybe?) to inform google forms submitter that his submission will not be gaethered because the form is restricted to selected google accounts?
My try looked like this, but it has 2 problems :
-it is accepting answers submitted from people other than verified and verified2 (no idea how to add that)
-it only displays my custom message if someone tries to submit second answer
function onFormSubmit(e){
var af = FormApp.getActiveForm();
var defaultClosedFor = af.getCustomClosedFormMessage();
af.setCustomClosedFormMessage("You are not using an account with submission access. Please log in to account with correct authorization");
var responses=af.getResponses();
if(responses[responses.length-1].getRespondentEmail()=="verified#gmail.com" ||
responses[responses.length-1].getRespondentEmail()=="verified2#gmail.com"
){
af.setCustomClosedFormMessage(defaultClosedFor);
}
}
I see multiple problems with the code:
Custom Closed Form Messages are only displayed when the form is closed for responses manually or the form only allows one response per email account.
Email addresses are not collected on the form. It has to be enabled manually on the Form settings.
Solution:
Enable Collect Email Addresses option on Google Form Settings:
Use setConfirmationMessage() to display custom messages depending on the entered email when the form is submitted.
Sample code:
function createTrigger() {
var form = FormApp.openById('****your-form-id****');
ScriptApp.newTrigger('validateForm')
.forForm(form)
.onFormSubmit()
.create();
}
function validateForm(e){
var af = FormApp.getActiveForm();
af.setCollectEmail(true);
var responses=af.getResponses();
var defaultConfirm = "Your response has been recorded.";
var rejectMessage = "You are not using an account with submission access. Please log in to account with correct authorization.";
if(responses[responses.length-1].getRespondentEmail()=="verified#gmail.com" ||
responses[responses.length-1].getRespondentEmail()=="verified2#gmail.com")
{
af.setConfirmationMessage(defaultConfirm);
}
else {
af.setConfirmationMessage(rejectMessage);
af.deleteResponse(responses[responses.length-1].getId());
}
}
Note: Please run createTrigger() first manually in GAS to create the on form submit trigger.

Google Apps Script - Email trigger not working outside domain

I have created a google form, went to response sheet - script editor - written script and activated a trigger to send email upon form submit, 'To' is as per the value entered in google form, 'cc' is by default 'raajesh#master-brains.com'. This is not working.
But, when I modify the script as 'To' and 'Cc' to raajesh#master-brains.com, I am receiving the trigger email. Why is it so? Is it working only within my domain of master-brains.com? What should I do to enable it for gmail / other domain accounts?
function myFunction(onboard) {
var conNo = onboard.values[3];
var conEmail = onboard.values[4];
var subject = 'Welcome Onboard as Master-Brains Connector | '+conName;
var htmlBody = 'Greetings from Master-Brains!!';
MailApp.sendEmail('raajesh#master-brains.com', subject, htmlBody, {'htmlBody':htmlBody, cc: 'raajesh#master-brains.com'})
}

Apps Script sends old feedback page, but new feedback inside email

I'm a beginner with Google app scirpts
i want send a feedback-page to users feedback typed into html form.
the script considers my changes into the email anwser.
but the feedback pages is always rendered with old form.html not the new antwortSeite.html.
should i use inside the forms also publish as webapp?
i do this with the Code.gs file.
i tried this but could not find any updates.
fileNameAntwortSeite = 'antwortSeite.html'; // <?= email ?>
var template = HtmlService.createTemplateFromFile(fileNameAntwortSeite);
template.email = 'huibuh#somebody.com';
antwortHtml = template.evaluate().getContent()
MailApp.sendEmail({to: kundenEmail, subject: 'test createTemplateFromFile'
, htmlBody: antwortHtml});
return antwortHtml;

How to persist Google Apps HtmlObject created with template.evaluate() to a URL?

I am using a Google Spreadsheet and its triggered App Script to compose and send daily status information in an html-formatted email. The email message body is composed using an html template into which token data are inserted from spreadsheet data and calculations. After insertion, the HtmlObject becomes the body of the email message using code like the following:
htmlBody = template.evaluate();
MailApp.sendEmail({
to: emailRecipients,
replyTo: emailReply,
subject: 'Today's Management Report',
htmlBody: htmlBody.getContent(),
});
I would also like to post the daily HtmlObject (Management Report) on our website but I cannot find a method to persist the object to a URL. Can anyone provide some guidance how to do this?
Thanks.
I will add to Jack Brown's comment above about deploying the HtmlObject as a Web app. Once you have deployed the HTML, you can get the URL with the ScriptApp service. The documentation provides an example close to what I think you are looking for: https://developers.google.com/apps-script/reference/script/service#getUrl()
// Mail the URL of the published web app.
MailApp.sendMail("myself#example.com", "My Snazzy App",
"My new app is now available at " + ScriptApp.getService().getUrl());
In case it helps others, here is the gs code I used to persist the blob and move it from Drive's root folder to its target destination folder:
// create pdf version of daily report
var title = "Daily Operations Summary - " + Utilities.formatDate(currStatusDate,'MST','MM/dd/yyyy') + ".pdf";
var htmlDaily = htmlBody.getContent();
var blob = Utilities.newBlob(htmlDaily, 'text/html').getAs('application/pdf').setName(title);
// save file and move to target folder
var fileID = DriveApp.createFile(blob).getId();
var destfolderID = "your Google folder GUID";
var file = DriveApp.getFileById(fileID);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(destfolderID).addFile(file);