Send Email based on column value = yes - javascript

I have a Google Sheet where the Email & Name columns are auto-fill based on user submitted form. Also, I have 2 more columns where one column contain the list of giveaway code and another column is to act as an approval to send the email.
So for now I manage to create a button where when click it will send all emails with the giveaway code.
Now,
How can I only send the email to the user that only has a value "y" in the Status column?
Also, after sending the emails, the value "y" will changed to "d"? So that later, if I use the function again, it will only sending to the new users.
This is the sheet example https://docs.google.com/spreadsheets/d/1KkShktBnJoW9TmIzNsAuAJb6XslBrMwJGEJu7xeF1fk/edit?usp=sharing
This is the code
function sendArticleCountEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Test1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:E1000");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var timeStamp = rowData[0];
var recipient = rowData[2];
var code = rowData[3];
var status = rowData[4];
var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
var subject = 'Here is your giveaway code!';
MailApp.sendEmail(emailAddress, subject, message);
}
}
/**
* The event handler triggered when opening the spreadsheet.
* #param {Event} e The onOpen event.
*/
function onOpen(e) {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Send Emails', functionName: 'sendArticleCountEmails'}
];
spreadsheet.addMenu('Send Emails', menuItems);
}

Just add an if statement like this:
function sendArticleCountEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Test1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:E1000");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var timeStamp = rowData[0];
var recipient = rowData[2];
var code = rowData[3];
var status = rowData[4];
var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
var subject = 'Here is your giveaway code!';
if (status == "y") {
MailApp.sendEmail(emailAddress, subject, message);
var actualRow = parseInt(i)+2;
sheet.getRange(actualRow,5).setValue("d");
}
}
}

Related

Send email based on cell value

I am trying to have this script loop per column. If a date in the column is the same as today's date, the script will send an email using the persons name and email address detailed in the same row.
Table of Expiry Dates
function myFunction()
{
var spreadSheet = SpreadsheetApp.getActiveSheet();
var dataRange = spreadSheet.getDataRange();
var data = dataRange.getValues();
var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
var engcheck1 = dataRange.getColumn[2];
for (var i = 1; i < data.length; i++)
if (engcheck1 == date)
{
var row = data[i];
var emailAddress = row[7]; //position of email header — 1
var name = row[1]; // position of name header — 1
var subject = "Your Currency for Engineering is now expired";
var text = "Please note that your currency has expired today (" + date +"). You are now unauthorised to carry out any engineering tasks until you have been signed off by a member of the engineering team.";
var message = "Dear " + name + "," + "\n\n" + text + "\n\n" + "Please get back in currency at your earliest convenience." + "\n\n" + "Many thanks," + "\n" + "Dominic Paul"
MailApp.sendEmail(emailAddress, subject, message);
}(i);
}
Without the 'If' statement, the script will loop through each row and sending out an email address. When I include the 'If' statement, nothing is sent to the email addresses. Either I am using the if statement incorrectly or I am not targeting the column accurately. I tried creating a variable engcheck1 for column 2 ONLY but no email is sent despite today being one of the dates in column 2 (C).
I did not understand, what is var engcheck1 = dataRange.getColumn[2];.
If you need to send and email if date is the same as the value in C column, provided column C has type Plain text, this is the answer:
function myFunction() {
var spreadSheet = SpreadsheetApp.getActiveSheet();
var dataRange = spreadSheet.getDataRange();
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getDataRange().getNumRows();
var dateData = spreadSheet.getRange("C1:C" + lastRow).getDisplayValues().flat();
var data = dataRange.getValues();
var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
for (var i = 1; i < data.length; i++) {
var rowDate = dateData[i];
var row = data[i];
// if the date in row is the same as date variable
if (rowDate === date) {
var emailAddress = row[7]; //position of email header — 1
var name = row[1]; // position of name header — 1
var subject = "Your Currency for Engineering is now expired";
var text = "Please ...";
var message = "Dear ...";
MailApp.sendEmail(emailAddress, subject, message);
};
}
}
Try this:
function myFunction() {
const ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rg = sh.getDataRange();
var vs = rg.getValues();
const dt = new Date();
var dtv = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
vs.forEach((r,i) => {
let d = new Date(r[2]);
let dv = new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf();
if(dv == dtv ) {
//send you email
}
})
}

Trying to write a script where column h if true would return a value of same row column a to display in email message

Been playing around with this and i am new to this unfortunately. So my goal is if a row in column h is true, in the email message it would get the value of the same row as column h and display what would be column a as the message.
ALL HELP IS THOROUGHLY APPRECIATED
function CheckSales() {
// Fetch the repair scba
var monthSalesRange =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("H1:H20");
var monthSales = monthSalesRange.getValue();
var ui = SpreadsheetApp.getUi();
// Check totals sales
if (monthSales = true) {
sendEmail();
}
}
function sendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("B2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'A bottle is in need of repair!'; // Second column
var subject = 'SCBA Repair Email';
MailApp.sendEmail(emailAddress, subject, message);
}
It sounds like your spreadsheet looks like:
A
B
...
H
Message to send
Target email address
...
True/False
For rows where column H is true, you want to email the message in column A to the user in column B.
If that understanding is correct, this should do the trick:
function generateEmails() {
var dataRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A1:H20");
var data = dataRange.getValues();
var subject = 'SCBA Repair Email';
for (var i = 0; i < data.length; i++) {
var row = data[i];
if (row[7]) {
var recipient = row[1];
var body = row[0];
MailApp.sendEmail(recipient, subject, body);
}
}
}

Google Script Email with CC

I'm having an issue where I want to be able to send an email with CC's based off cell values. i.e. both the main recipient email and CC email are in the spreadsheet in the same row. The code should cycle through each row and send an email to the recipient and attaches the CC to that email.
My code is as follows:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // Start at second row because the first row contains the data labels
var numRows = 10; // Put in here the number of rows you want to process
// Fetch the range of cells A2:B4
// Column A = Email Address, Column B = First Name
var dataRange = sheet.getRange("A2:C")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var name = row[0];
var emailAddress = row[1];
var daysAbsent = row[2];
var CC = row[3];
var message = "Hi " + name + ",\n. We see that you have been absent for " + daysAbsent + " days.";
var subject = "Attendance Notification";
MailApp.sendEmail(emailAddress, subject, message,{
cc: CC
});
}
}

Google scripts for Spreadsheets (If statements)

I am hoping someone can help me with this issue. I am new to coding. I have a google spreadsheet with a script that pushes out an email. I am attempting to have the script ignore the rows where the script has already sent out an email on.
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Email Menu')
.addItem('Send Email', 'myFunction')
.addSeparator()
.addToUi();
};
function myFunction() {
var msg = 'Email sent!';
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
var EMAIL_SENT = "EMAIL_SENT";
var startRow = 2;
for (i=1; i<values.length;i++) {
//sent = values[i][4]; //added this in to try and skip a row if "X" was in Sent Column
//if (sent ==" ", ) //added this in to try and skip a row if "X" was in Send Column
var email = values[i][0];
var name = values[i][i];
var subject = values[i][2];
var body = values[i][3];
var sent = values[i][5];
if (sent != EMAIL_SENT){
MailApp.sendEmail(email, subject, body);
sheet.getRange(startRow + i,5).setValue(EMAIL_SENT);
SpreadsheetApp.getUi().alert(msg);
}
}}
Google spreadsheet
Implement the following changes in your for loop:
for (i=1; i<values.length;i++) {
var email = values[i][0];
var name = values[i][1]; //not [i][i] !
var subject = values[i][2];
var body = values[i][3];
var sent = values[i][4];
if (sent !== EMAIL_SENT){
sheet.getRange(i+1,5).setValue(EMAIL_SENT);
}
}
Basically get rid of the startRow variable (if you are not using elsewhere) and just use (i+1,5) to place "EMAIL_SENT" in the right column. I have removed parts of your code for the sake of clarity.
Small fix. Replace
sheet.getRange(startRow + i,5).setValue(EMAIL_SENT);
to
sheet.getRange(startRow + i - 1, 6).setValue(EMAIL_SENT);
According to the rest of the script, this should be the most simple fix. This assumes sent column is F (column 6) not E (column 5). Sample sheet including updated script is here.
And! You should change var name = values[i][i]; to var name = values[i][1]; as #jrook pointed. I missed it...

google apps script that sends sms from spreadsheet data

I'm wondering if anyone has already put together a script that simply takes a phone number from a cell and sends a text message. Just the same as if it were an email address. Using the carriers email extension is not the solution I'm looking for but if someone has figured out how to programmatically figure out the carrier extension, add it to the phone number, then that would work too.
Example I'm using for sending an email
function inventory() {
var sheet = SpreadsheetApp.getActiveSheet()
var row = sheet.getActiveRange().getRowIndex()
var firstName = sheet.getRange(row, getColIndexByName("First Name")).getValue();
var lastName = sheet.getRange(row, getColIndexByName("Last Name")).getValue();
//var phone = sheet.getRange(row, getColIndexByName("Phone Number")).getValue();
var email = sheet.getRange(row, getColIndexByName("Email Address")).getValue();
var inventoryLinks = sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
//var userEmail = 'put email here';
var subject = "Your Inventory List";
var body = "Hello"
+ "\n\n" + "Please follow the supplied links below to see the listings that fit your profile."
+ "\n\n" + sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
MailApp.sendEmail(email, subject, body, {name:"Inventory List"});
}
function getColIndexByName(columnName) {
var sheet = SpreadsheetApp.getActiveSheet();
var numColumns = sheet.getLastColumn();
var row = sheet.getRange(1, 1, 1, numColumns).getValues();
for (i in row[0]) {
var name = row[0][i];
if (name == columnName) {
return parseInt(i) + 1;
}
}
return -1;
}
So I want to accomplish the same thing replacing the email address with a phone number
This is what I ended up with. Works Great!
function sendSMS() {
// Get account SID and auth token here:
// https://www.twilio.com/user/account
// Also, you have to buy a paid account to send SMS to any phone number. Otherwise you can only send to verified numbers
// So this script allows me to put my cursor in the row I want to send an SMS.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var phone = sheet.getRange(row, getColIndexByName("Phone")).getValue();
var inventoryLinks = sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
var sentSMS = sheet.getRange(row, getColIndexByName("Sent SMS")).getValue();
var comments = sheet.getRange(row, getColIndexByName("Comments")).getValue();
var activeUser = Session.getActiveUser().getEmail();
var extphone = "+1" + phone;
var body = "Click on the link/s to see current inventory. " + inventoryLinks;
var accountSid = "get it from your Twilio account";
var authToken = "get it from your Twilio account";
var url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/SMS/Messages.json";
var options = {
method: "post",
headers: {
Authorization: "Basic " + Utilities.base64Encode(accountSid + ":" + authToken)
},
payload: {
// From is one of your Twilio phone numbers
From: "Put you Twilio number here",
To: extphone,
Body: body
}
};
sheet.getRange(row, getColIndexByName("Sent SMS")).setValue('Sent SMS').setComment(new Date() + activeUser);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}

Categories