Conditional Emails from google forms spreadsheet - javascript

I am trying to send conditional emails to people who submit a google form based on their responses.
Essentially, I need a code that reads one column and then sends an email message to the email address they supply. I need it to do this every time the form is submitted.
Here is what the sheet looks like: four column google sheet with timestamp, name, email address, and state fields
This is my first script so I've figured out how to send an email by pointing to a specific cell, but am having trouble figuring out how to have it trigger each time the form is submitted and how to point it to a full column rather than a specific cell.
Here is some code I've written that does not work. I'm really new to this so I'm sure there are plenty of beginner mistakes. :
var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("myFunction")
.forSpreadsheet(sheet)
.onFormSubmit()
.create();
if (lastRow.getvalues() == "NY") {
function SendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange("C2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your NY Alert email!'; // Second column
var subject = 'Your NY Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
} }
else (lastRow.getvalues() == "MA") {
function SendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange("C2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your MA Alert email!'; // Second column
var subject = 'Your MA Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
Thank you for any help, insight, or resources!

Try this:
function createTrigger() {
var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("myFunction")
.forSpreadsheet(sheet)
.onFormSubmit()
.create();
}
function myFunction(e) {
const list = ["NY", "MA"];
if (~list.indexOf(e.values[3]) {
MailApp.sendEmail(e.values[2], 'Your NY Google Spreadsheet Alert', 'This is your NY Alert email!');
}
}
Spreadsheet onFormSubmit Event Object

Related

Google sheet Automation

Can you please help me, How to send dynamic mail every latest entry in google sheet?
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A2:C4");
var UserData = range.getValues();
for (i in UserData) {
var row = UserData[i];
var name = row[0];
var email = row[1];
var score = row[2];
MailApp.sendEmail(row[1], "Custom mail", "Hello " + name + ", This is an email report of your score. Your score is " + score);
}
}
Setup a trigger in your project: Trigger for "form submission". Whenever someone submits the form, script will send out the email to those whom the email wasn't sent. Also have a helper column in the sheet to update status for the script to filter out the people who already received the email, else others will keep receiving their scores everytime there's a form submission.

Setting up an email system from my google spreadsheet. I have everything else working except for adding an image into the body

I'm trying to add an image into the body of the emails. I've been able to get everything else working fine besides the image part. The images I'm trying to use are in the "M Column".
What do I need to add to get the value from the "M Column" and put it into the body of the emails?
-code is provided below
Thanks in advance. Everything I've tried has failed so I just removed everything I attempted and went to what I originally had before I decided to add images to the emails.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 15;
var dataRange = sheet.getRange(startRow, 1, numRows, 15);
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[4];
var message = row[10];
var subject = "Subject Test";
MailApp.sendEmail(emailAddress, subject, message);
}
}
[error message][1]
[1]: https://i.stack.imgur.com/nwAJG.png
If you want to send an email which contains images, you could use one of the following options:
If your images are stored as urls in your Spreadsheet
The following code snippet is used to create the attachment containing the image gathered from a url stored in your Spreadsheet.
var imageUrl = sheet.getRange("YOUR_RANGE_FOR_THE_IMAGE").getValue();
var imageBody = "<img src='cid:myImage'>";
var imageBlob = UrlFetchApp.fetch(imageUrl)
.getBlob()
.setName("imageBlob");
var message = row[10];
var subject = "Subject Test";
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: message +"<br/><br/>"+ imageBody,
inlineImages:{
myImage: imageBlob
}
});
The above code snippet uses InlineImages in order to attach the image as an attachment into the email you want to send.
If your images are stored in drive and you have their file ids
The following code snippet is used to create the attachment containing the image gathered from the id of the file which is stored in Drive.
var imageId = sheet.getRange("YOUR_RANGE_FOR_THE_IMAGE").getValue();
var image = DriveApp.getFileById(imageId);
var imageBlob = Utilities.newBlob('', 'image/jpeg');
var message = row[10];
var subject = "Subject Test";
MailApp.sendEmail({
to: emailAddress,
subject: subject,
body: message,
attachments: [image.getAs(MimeType.JPEG), imageBlob]
});
If your images are stored inside a cell and/or as overgrid images
Unfortunately, Google Sheets doesn't have the capacity to return the blob of an image, only a reference to the image which means that you cannot retrieve the images and attach them afterwards in an e-mail using Google Apps Script.
In this case, an alternative would be to use the =IMAGE() function to insert the images in a cell and afterwards you can retrieve them by using the Sheets API V4.
Reference
MailApp Class Apps Script;
Sheets Class Apps Script getRange;
DrivApp Class Apps Script getFileById;
Apps Script Reference;
Sheets API.

Google apps script update specific cell based on if statement

Currently, my script is updating all cells within the selected range with "YES" but I only want it to update cells that meet the if conditions. Any help would be much appreciated.
//Active spreadsheet var that can be used anywhere in the programme
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get and check if there is an email address
function checkSendEmailAdd () {
//Getting the array of values
var activeSheet = ss.getActiveSheet();
var emailCol = activeSheet.getRange(2, 9, activeSheet.getLastRow() - 1, 2).getValues();
//Looping over the array of values
emailCol.forEach(function(val){
var email = val[0].toLowerCase();
var sentEmail = val[1];
//If the send date column is empty and the email column has a # within the string an email will be sent
if (email.indexOf("#") !== -1 && sentEmail == ""){
//Email contents
var subject = "Survey";
var body = "Hi" + "<br><br>" +
"Testing 123";
GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
//Update and set a new value in the sent email column
var newSetValue = "YES";
var updateSentEmail = activeSheet.getRange(2, 10, activeSheet.getLastRow() - 1, 1).setValue(newSetValue);
} else {
}
});
The problem I'm facing is that the sent column is updating every cell but I only want it to update the cells that have an email in the email column.
Image of what is being executed currently
Try it this way:
I tried to determine the columns from your question. I believe email was column one and sentMail was column two but if I'm wrong you can change them to whatever you need.
function sendEmail() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet0');
var vA=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
var sentA=sh.getRange(2,2,sh.getLastRow()-1,1).getValues();
var html='';
for(var i=0;i<vA.length;i++) {
var email=vA[i][0].toString().trim().toLowerCase();
var sentEmail=vA[i][1];
if(email && email.indexOf("#")>-1 && !sentEmail){
var subject = "Survey";
var body = "Hi<br><br>Testing 123";
//GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
html+=Utilities.formatString('<br />%s -<br />Email: %s<br />Subject: %s<br />Body: %s<br /><hr/>', Number(i+1),email,subject,body);
sentA[i][0]="Yes";
}
}
sh.getRange(2,2,sh.getLastRow()-1,1).setValues(sentA);
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Emails Sent');
}
Spreadsheet before sending:
Spreadsheet after sending:
I removed the Gmail line and used a dialog to display the emails:

google apps script - form not automatically mailing spreadsheet response

I am new to Google Scripts but am getting the gist of it pretty quickly. I am trying to automate ordering of toner for our commercial printer. I set up a Google Form with 4 scale questions, one for each color (CMYK), with multiple choices from 1 through 5 toner cartridges.
Then, in the Google Spreadsheet that records responses, I created a script (mainly from internet examples) that gets the last entry of the spreadsheet (bottom row) and sends an email with the amount of toner cartridges needed, with a trigger onFormSubmit().
When I use the form and hit the submit button, nothing happens. There seems to be a disconnect between the form and the spreadsheet? Maybe some triggers are not working? I tried using the triggers from the script editor and also the programmable triggers and it still does not work from the form submission.
The "ScriptApp" part of the script's trigger doesn't seem to be recognized by the Google Scripts editor, as it's not in a particular color, different from the other code, which makes me wonder if I have to write some form of #include statement or something? All the internet examples show ScriptApp in color.
No bugs are found when "compiling"...
function sendFormByEmail(e)
{
ScriptApp.newTrigger("sendFormByEmail").forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onFormSubmit().create();
var email = "example#email.com";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,2,1,s.getLastColumn()-1).getValues()[0];
var colors = s.getRange(s.getLastRow(),2,s.getLastRow(),s.getLastColumn()-1).getValues()[0];
var message = "";
var subject = "Toner order";
for(var i in headers)
message += headers[i] + ': ' + colors[i] + "\n\n";
MailApp.sendEmail(email, subject, message);
}
This is the answer that definitely works. Had to clear past triggers first, else it would send multiple emails because it was creating a new trigger with each submission:
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("sendFormByEmail").forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onFormSubmit().create();
function sendFormByEmail(e)
{
var email = "example#email.com";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,2,1,s.getLastColumn()-1).getValues()[0];
var colors = s.getRange(s.getLastRow(),2,s.getLastRow(),s.getLastColumn()-1).getValues()[0];
var message = "";
var subject = "toner order";
for(var i in headers) {
message += headers[i] + ': ' + colors[i] + "\n\n";
}
MailApp.sendEmail(email, subject, message);
}

How do I make a response email be from the person submitting (Google App Script)

I have a Google form which submits to a spreadsheet. I then have written this code which sends an email with the results. Can anyone tell me how I make the email be submitted by the person who submitted the form?
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, subject, columns;
var message, value, textbody, sendername, sender;
// This is my email address and I will be in the CC
cc = e.namedValues["Username"].toString();
// This will show up as the sender's name
sendername = e.namedValues["Name"].toString();
subject = "Ticket Submitted";
message = "We have received your details.<br>Thanks!<br><br>";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Username"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] ) {
message += key + ' :: '+ e.namedValues[key] + "<br />";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
This is not possible, nor it should be. You want to impersonate someone else without their consent.
The archaic email system unfortunately allows that, therefore making easier the life of spammers and phishing scams. But Google and other Internet companies work hard to prevent and filter this kind of emails.
Bottom line, you will not be able to send an email as somebody else from a Google app unless it's an authorized account in your Gmail.
The best you can do is set the reply-to address.

Categories