Google apps script update specific cell based on if statement - javascript

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:

Related

Conditional Emails from google forms spreadsheet

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

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.

Googlesheets script: mailApp sending multiple emails to specified cc email

I'm trying to send an email with inline images to a series of users with myself in cc (myself#hotmail.com). I am trying to do this with the code written bellow. Everything seemed to work, but as soon as I added cc: 'myself#hotmail.com' it broke. My email gets send to the recipient 1x, but also to 'myself#hotmail.com' 8x. I cannot figure out what I am doing wrong, any help is much appreciated.
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails").activate(); //makes sure your google sheets has the correct sheet open where you specify the emails and names
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); //defines spreadsheet to use
var lr = ss.getLastRow(); //gets last row on which there is data
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Template').getRange(1, 1).getValue() //gets email body from sheet 'template' which is defined in cell 1,1 -- make sure your sheet has same name else it won't work
var quotaLeft = MailApp.getRemainingDailyQuota(); //gets number of emails that you can still send
// Image URLs
var img1Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
var img2Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
// Fetch images as blobs, set names for attachments
var img1Blob = UrlFetchApp
.fetch(img1Url)
.getBlob()
.setName("img1Blob");
var img2Blob = UrlFetchApp
.fetch(img2Url)
.getBlob()
.setName("img2Blob");
//embeded image tags for email
var bodyImg1 = "<img src='cid:img1' style='width:1000px; height:1500px;'/>"; //specify img size here
var bodyImg2 = "<img src='cid:img2' style='width:1000px; height:1500px;'/>"; //specify img size here
if((lr-1) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " left and you're trying to send " + (lr-1) + " emails. Emails were not send"); //gives standard warning message if number of emails to be send exceeds limit
} else {
for (var i = 2; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue(); //gets email in excel sheet
var currentName = ss.getRange(i, 2).getValue(); //gets name in excel sheet
var subjectLine = "Invitation"; //title of email
var messageBody = templateText.replace("{name}", currentName); //replaces name in template with name of current cell, see templateText var
MailApp.sendEmail(currentEmail, subjectLine, subjectLine, {htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}, cc: 'myself#hotmail.com'});
} //close for loop
} //close else statement
} //close function
Solution:
MailApp.sendEmail({ to: currentEmail, subject: subjectLine, cc: 'myself#hotmail.com', htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}});

Want to make the script send email only to the last added one in Google Spreadsheets

This is a script to send emails to the contacts I saved in googlespreadsheets. However, I want it only to send it to the last added email (not all the list). It keeps sending it to everyone included in the list and I want only to send to the last added email in row[2] where are the emails registered.
Thanks.
function sendEmail(e) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var data = ws.getRange("A2:D" +ws.getLastRow()).getValues();
data.forEach(function(row) {
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var subject = "Thanks for participation";
var textBody = "This email requires HTML support. Please make sure you open with a client that supports it.";
var options = { htmlBody : htmlText };
GmailApp.sendEmail(row[2], subject, textBody, options);
});
}
This will only email the last row every time.
function sendEmail(e) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var data = ws.getRange(2,1,ws.getLastRow()-1,4).getValues();
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var subject = "Thanks for participation";
var textBody = "This email requires HTML support. Please make sure you open with a client that supports it.";
var options = { htmlBody : htmlText };
GmailApp.sendEmail(data[data.length-1][2], subject, textBody, options);
}
if you do it this way then it will only use that line once unless you edit it with additional emails.
function sendEmail(e) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var data = ws.getRange(2,1,ws.getLastRow()-1,4).getValues();
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var subject = "Thanks for participation";
var textBody = "This email requires HTML support. Please make sure you open with a client that supports it.";
var options = { htmlBody : htmlText };
if(data[data.length-1][2]) {
GmailApp.sendEmail(data[data.length-1][2], subject, textBody, options);
ws.getRange(data.length-1+2,3).setValue('');
}
}

Open Jquery dialog from inside Ajax request?

I have a problem with my current javascript/ajax request. I'm trying to open a Jquery dialog from inside my .append my code follows:
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var NewEdit = row[0];
var PreviousEdit = row[1];
var FunctionName = row[2];
var FunctionID = row[2]
function ShowInfo()
{
dialog('Original: <br>'+PreviousEdit+'<br><br> New: <br>' +NewEdit);
}
$('#RecentEdits').append("<br>Page: "+FunctionName+" - <a href='#' OnClick='ShowInfo()'>Info</a>");
}
I have only pasted relivant code, if required I can post the entire function.
I know for a fact, my variables are correctly set due to them being printed out.
How can I open up a Dialog box showing more information from inside a Javascript function?
Solution:
As there is no correct replies. I have used OQJF's example and produced this:
<script>
function ShowInfo(a,b)
{
alert('Original: \n'+unescape(a)+'\n\n New: \n'+unescape(b));
};
</script>
<script>
//window.setInterval(function()
//{
$(function ()
{
$.ajax({
url: 'RecentUpdates.php', data: "", dataType: 'json', success: function(rows)
{
$('#RecentEdits').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var NewEdit = row[0];
var PreviousEdit = row[1];
var FunctionName = row[2];
var FunctionID = row[3];
$('#RecentEdits')
.append("<br>Page: <a href='Page.php?ID="+FunctionID+"'>"+FunctionName+"</a> - ");
$('#RecentEdits').append("<input type='button' onClick=ShowInfo('"+escape(PreviousEdit)+"','"+escape(NewEdit)+"'); value='Show'>");
}
}
});
});
// }, 1000);
</script>
which has enabled me to access the function from my Javascript printout.
I had troubles with the quotes wrapped around my html so i have decided to make two appends. And this seems to work just fine!
While firstly I think you should set the function showInfo outside of the loop and set 2 parameter for it. Below is the sample code that I didn't test but It should be almost like this.
function ShowInfo(orginVal,newVal)
{
var msg =('Original: <br>'+orginVal+'<br><br> New: <br>' +newVal);
$(<div>msg</div>).appendTo('body).dialog();//maybe you can add some options for dialog
}
below part seems be in another function.
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var NewEdit = row[0];
var PreviousEdit = row[1];
var FunctionName = row[2];
var FunctionID = row[2]
$('#RecentEdits').append("<br>Page: "+FunctionName+" - <a href='#' OnClick='ShowInfo(/*add your 2 parameters here*/)'>Info</a>");
} s

Categories