Delete the emails stored in a Google Form's responses - google-apps-script

Background:
I am trying to create a google form that will be filled out by people, and then send a second form to be filled by someone else (couple). The form response needs to be anonymous, but the responses will also need to be linked.
My solution so far - using a unique ID for linking (kudos -> How to assign a unique ID to a google form input?) then using the email inputted to send off a message with a pre-made link to the next form with the ID and then delete the email address from the sheet.
The Question
The next sanitation which I am stuck on - is removing the email address form the Google Form response. One way would be to use deleteAllResponses() but that will also delete the basic data analysis pre-done by Google that I intend to use (to save time on creating some of the graphs).
I tried to find a way to access the response object and delete/modify the email field, but was unable to achieve that.
Would appreciate the help.
function myFunction() {
//delete the last email that was added
function deleteEmails(Row){
sheet.getRange('B'+Row + ':B'+Row).clearContent();
}
//delete all responses - would like to change this to only delete/modify the email field.
function deleteResponses() {
var form = FormApp.openById('The form ID');
form.deleteAllResponses();
}
//get the data on the sheet
var sheet = SpreadsheetApp.openById("The sheet ID").getSheetByName('Form Responses 1');
var StartRow = 1;
var LastRow = sheet.getLastRow();
var Range = sheet.getRange(LastRow, 2, 1, 62)
var AllValues = Range.getValues();
//if the person disagrees to fill the form - dont send an email
if (AllValues[0][1] != 'disagree') {
var SendTo = AllValues[0][0];
var body = "Thank you for answering pfa a link for the sedond form";
//send the actual email
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: 'Thank you for answering',
htmlBody: body,
});
}
//delete emails and responses
deleteEmails(LastRow)
deleteResponses()
}

Related

Google Sheet to send an email when cell has specific value

I have a Google Form for students to input data and I would like an email sent to myself or another person if a specific question has a certain answer. In the email I would like the name of the student that submitted the form to be included in the email. The problem I'm having is the email is only sending the information from Line 2 of my Sheet. (I have line 1 Frozen as headers). I need it to pull from the last line of data entered from the Google Form.
Google Form - https://docs.google.com/forms/d/1r1Tsyfl71zfzgzhs3-_qFB57FcSSEX1zS5BkTgz-ESA/prefill
Google Sheet Data - https://docs.google.com/spreadsheets/d/1P1RD7My91jLSHS9hgEOBPv5oYnfCJQviN6Nzy_cH7Cc/edit?usp=sharing
Here is my script code:
function CheckStudent(e) {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("B2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
{
var studentData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange("C2");
var studentData = studentData.getValue();
var message = studentData + ' is not doing well today!' // Second column
var subject = 'Student Daily Check Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
If you are already registering the email in the sheet submitted by the form, then is as easy as creating a installable trigger.
You can do that using the event object.
If you are unfamiliar with triggers then I recommend you to have a read at the official documentation in there you can see a few examples of how to create them:
var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("CheckStudent") // You will need to adapt your function
// to recieve the event parameter
.forSpreadsheet(sheet)
.onFormSubmit()
.create();
Once you have executed the previous code then your function will trigger every time someone submit the form.
EDIT
Now taht I think about you can just do the trigger directly in the form object not going through the sheets.
Changing the event object code slighlty:
var form = FormApp.getActiveForm();
ScriptApp.newTrigger('CheckStudent')
.forForm(form)
.onOpen()
.create();

Automated emailing using information from a google form and different spreadsheets?

I'm new to google scripts so please bear with me. I'm working on automating communication for a 2 condition study signup using a google form and google sheets. Essentially, when a participant submits a form, I need to send a confirmation email (trigger is form submission) with the date they chose, and a new unique ID based on their condition (I have two separate lists of premade IDs I need to use). Right now, I have the main form response sheet and then I'm using = query to separate the survey responses into sheets for the two conditions based on a multiple choice question in the survey ('Morning' and 'Evening'). I have the ID lists filled into the corresponding sheets so that when the = query sorts the responses, they are automatically "assigned" an ID as the rows fill. I have the code working to send emails without the IDs, just using the name and date in the first sheet of the spreadsheet (the form response sheet), but am running into problems grabbing the ID from the other corresponding sheet to put into the email.
Here is what I have:
function IntialEmails(e){
var ss = SpreadsheetApp.openById('MyownSpreadsheetID'); //not including real ID for privacy reasons
var type = e.values[4];
if (type == 'Condition A') {
var sheet = ss.getSheets()[1];
ss.setActiveSheet(sheet);
}
if (type == 'Condition B') {
var sheet = ss.getSheets()[2];
ss.setActiveSheet(sheet);
}
var userName = sheet.values[0];
var userEmail = sheet.values[2];
var date = sheet.values[4]; //Using date from corresponding spreadsheet based on survey format
var ID = sheet.values[5]; // Should be from corresponding sheet
var subject = "Study Signup Confirmation and Participant ID";
var templ = HtmlService
.createTemplateFromFile('My html'); //not including real ID for privacy reasons
templ.date = date;
templ.ID = ID;
templ.userName = userName;
var message = templ.evaluate().getContent();
MailApp.sendEmail({
to: userEmail,
subject: subject,
htmlBody: message
});
}
I am super stuck, and continuously getting errors. This code throws back the error 'TypeError: Cannot read property '0' of undefined' If anyone can help me out it would be much appreciated!
If you want to get a value from a sheet you can do something like this:(Even I wouldn't normally do it this way I'm kind of following the same method that you used. I'm going to assume that you have your id's or what ever data in rows. But obviously I don't know since you didn't provide that information.
function initEmails(e) {
var ss=SpreadsheetApp.getActive();
var shts=ss.getSheets();
var sh=(e.values[4]=="Condition A")?shts[1]:shts[2];
var vs=sh.getRange(1,1,sh.getLastRow(),7).getValues();
for(var i=0;i<vs.length;i++) {
if(vs[i][7]!='USED') {
var userName=vs[i][0];
var userEmail=vs[i][2];
var date=vs[i][4];
var ID=vs[i][5];
var subject = "Study Signup Confirmation and Participant ID";
sh.getRange(i+1,8).setValue('USED');//this provides a way to keep track of which row was used last
}
/*.............I have no idea what your trying to do beyond this point.
}
But I don't think that you going to be able to insert these values into your html template this way:
templ.date = date;
templ.ID = ID;
templ.userName = userName;
Normally, templates are filled with desired data during the evaluate process by using scriptlets.
Templated HTML

Google form to answer sheet to separate sheet to email

I am trying to work out a solution to something and whilst I can get snippets of help from the weeb I cannot pin it down to what I want it to do. So, what I want to achieve:
A google form is submitted which creates a record in a google spreadsheet.
using the query function I take that information instantly to another sheet in the same spreadsheet. Whilst in there it goes through some if statements which creates a unique ID for the submission, separates the date and the time of the submission into separate columns and adds a email address that needs to be notified of this submission. For the purpose of this test, the submitter and the notification emails are the same.
the script monitors the second sheet and, on form submission (trigger), takes the information from the last row in a certain sequence to create an email:
function formsubmission(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetbyName('email');
var startRow = 2;
var lastRow = e.sheet.getLastRow();
var formid = e.sheet.column[1];
var notificationemail = e.sheet.column[2];
var formdate = e.sheet.column[3];
var formtime = e.sheet.column[4];
var submitter = e.sheet.column[6];
var yn = e.sheet.column[7];
var subject = formid + "submitted";
var message = "Thank for answering" + yn + "on" + formdate + "at"+ formtime;
MailApp.sendEmail (notificationgroup, subject, message,{
cc: submitter,
});
}
Needless to say that the above script does not work.
If any of you kind people want to help. The form is test form to which the above refers is here and the related spreadsheet is here.
I would prefer not to have a separate sheet but the one accepting submissions does not allow for any functions or anything else in it.
Any help to make the above script work would be greatly appreciated.
Thank you

Send HTML email from google spreadsheet using a button

I am new to stack overflow and am looking for some advice and some guidance on a google spreadsheet i have been working on.
A demo of it can be found at
https://docs.google.com/spreadsheets/d/1t9WfcG_1_mAavpN0l3v58JdD04Y1lL3PhAEoTUkq0Z4/edit?usp=sharing
Basically the jist of it is that i require the following.
A sendEmail button in the tool bar at the top that will send a html formatted email to any email on the active page in a specific colour.
Essentially this is to allow me to send reminder to clients in groups and by colour status. Currently i have to mail each client individually using a canned response which is pretty time consuming.
So far i am using the following script as a basis, i can successfully send an email but i run into errors if email fields are empty. I am looking for it to overlook the empty fields and continue searching for an email address. Also i can only get it to locate a template of an active sheet but would require it to locate a template of another sheet and use that. Finally when i try adding in HTML the script successfully picks up the template but sends it as plain text and its not sent as HTML.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 100; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 100)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[8]; // Eight column
var message = row[15]; // Fifteenth column
var subject = "Welcome To Phorest";
MailApp.sendEmail(emailAddress, subject, message);
}
}
Looking forward to speaking with someone that can help me work all this out and save me some data entry in the process.
Appreciated.
You can send an HTML-containing email the following way:
var email = "some#email.com";
var subject = "Hello!";
var html = '<p> What is your favourite fruit? </p> <br>' +
'<select>' +
'<option value="apple">Apple</option>' +
'<option value="orange">Orange</option>' +
'</select> ';
MailApp.sendEmail({
to: email,
subject: subject,
htmlBody: html
});

Google Script to email form answers and questions to a user

I am trying to make a simple script that sends an email to a user who fills out a survey through a Google Form.
They will take the survey, answers are recorded in a spreadsheet, and this script will email them a copy of the questions (the headings), along with their answers (Should be the last row of the table.)
The email it is sent to was going to be the last column, which is not included in the email.
This was the script I was working on to get this working:
function sendFormByEmail(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var emailSubject = "EMAIL-SUBJECT-HERE";
var yourEmail = "CURRENTLY-JUST-A-STATIC-EMAIL-ADDRESS"; //get this from a field.value then just cut off that field from being included in the email (just do column-1)...
var headers = headersRange.getValues()[0]; //google api to get the header values.
var lastRow = s.getLastRow();
var message += headers.toString();
message += (headersRange.getValue()[last]).toString(); //should get the last row of data?
MailApp.sendEmail(yourEmail, emailSubject, message);
}
Add a trigger that executes whenever a form is submitted and attach this function to your trigger.
In your code, you can use e.values[] in your code to refer to the values submitted by the user. This way you will not have to read the spreadsheet
function sendFormByEmail(e) {
var email = e.values[0]; // assuming 1st field is email
var firstName = e.values[1]; // assuming 2nd field is first name
...
}
You will probably find it hard to read the results of an email with all the questions in one line, and all answers in another.
It's easy to loop through the headers & form values at once, and just skip over the email address if you wish.
function sendFormByEmail(e) {
var emailSubject = "EMAIL-SUBJECT-HERE";
var emailQ = 1; // Column number with email address
var headers = SpreadsheetApp.getActiveSheet().getDataRange().getValues()[0]; //google api to get the header values.
var message = "Your survey responses:\n\n";
// Print Questions & Answers in pairs
for (i=0; i < headers.length; i++) {
if (i == emailQ) continue; // skip email address
message += headers[i]+"\n"
+ e.values[i]+"\n\n";
}
MailApp.sendEmail(e.values[emailQ], emailSubject, message);
}