Email notification when date due expired - google-apps-script

first of all I would like to say that I am really a rookie at Apps Script.
I have found Script Code for automated Email notification when certain date is expired. I tried to alter the code for my SpreadSheet, but unfortunately it does not work properly for me:
function offboardingReminder() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// set active sheet to first sheet
spreadsheet.setActiveSheet(spreadsheet.getSheets()[0]);
var sheet = spreadsheet.getActiveSheet();
// figure out what the last row is
var lastRow = sheet.getLastRow();
var startRow = 2;
// grab all data from user to days left
var range = sheet.getRange(startRow, 1, lastRow - startRow + 1, 45);
var values = range.getValues();
var users = [];
// loop all data per row
values.forEach(function(row) {
// if days left is 3
if(row[45] <= 30) {
// add user if 3 days left
users.push(row[0]);
}
});
// if users has elements
if(users) {
// Formatted the message as html to look nicer
var message = "<html><body><h2>Reminder</h2><p>The following device/s service is due in 30 days or less:</p>";
// created bulleted list for list of users
var emails = "<ul>";
users.forEach(function(user){
emails = emails + "<li>" + user + "</li>";
});
emails += "</ul>";
message = message + emails + "</body></html>";
MailApp.sendEmail("norbert.jedrzejczak#kbcpl.pl", "Reminder Date Dues Services", "", {htmlBody: message, noReply: true});
}
}
So what I would like to accomplish here is to send automated notification every week with the list of expired services.
I have a spreadsheet with 51 columns and I would like to:
Take the name of the customer (column 31)
Take the date of last service (column 41)
Take the number of days left to next service (column 44) - and take these values which are equal or less than 30
And send a message with these data.
Subject: "Reminder Date Dues Services" + Current Date (of sending each email)
Body:
"Reminder! The following device/s service is due in 30 days or less:"
And below - a list of devices to be serviced - e.g. "CUSTOMER 1 - DEVICE 1 - SERIAL NUMBER 1 - DATE OF LAST SERVICE - DATE TO NEXT SERVICE"
Could you please help me out with the code? I would be grateful for your tips and recommendations.

Just to get you started:
function lfunko() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const sr = 2;
const vs = sh.getRange(sr,sh.getLastRow() - sr + 1, sh.getLastColumn()).getValues();
vs.forEach((r,i) => {
let n = r[30];
let dt = r[40];
let ds = r[43];
if(ds < 30 ) {
//complete message and email in here
}
})
}

Related

Google Apps Script - Send Email based on value in columns

I am new with Google App Scripts and have a spreadsheet with 2 columns: https://docs.google.com/spreadsheets/d/1J3IR3y7VemlrKNsJ8u0gzaUAZy6wBb7qncPfKkab4l4/edit#gid=0
The scripts I'm using:
function sendEmail() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1'); // change Sheet1 to the name of your sheet
const data = sh.getRange('A2:B'+sh.getLastRow()).getValues();
data.forEach(r=>{
let salesValue = r[1];
if (salesValue = 0){
let name = r[0];
let message = 'There are no sales for ' + name;
let subject = 'No SALES.'
MailApp.sendEmail('myemail#email.com', subject, message);
}
});
}
This works but sends me one email per each business name. So, based on the data in the sheet, I will get 2 emails.
I would like to send one email only to group of emails on a daily basis when the sales column (B) equals ZERO. Assume that the sheet is updated daily and I want to set a trigger to run the script daily.
Your email send is in the forEach loop so every row that is zero (change the if comparison to ==) it is sending the email. Bring that to the bottom and you'll just get one email. This might get you closer to what you're looking for:
function sendEmail() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1'); // change Sheet1 to the name of your sheet
const data = sh.getRange('A2:B'+sh.getLastRow()).getValues();
let zeroSales = []
data.forEach(r=>{
let salesValue = r[1];
if (salesValue == 0){
let name = r[0];
zeroSales.push(name)
}
});
if (zeroSales.length > 0) {
let subject = 'No SALES.'
let message = 'There are no sales for ' + zeroSales.join(', ')
MailApp.sendEmail('myemail#email.com', subject, message);
}
}

Sending the number of products via email in Google Sheets

I have a google sheets tool where I automatically get the number of products on our site every hour with the Shopify API.
https://docs.google.com/spreadsheets/d/1m1lF6jLWPIKhJDOut_G-2tX_zYW4fU9dHKwIs03rr1Y/edit?usp=sharing
I need to develop a code for this tool. This code will check this product number after each product number search and if this product number is below 1000, it should send me a mail informing the product number. How can I improve this?
The function that takes the number of products from the site
function _1() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var startCol = 1
var lastRow = spreadsheet.getLastRow();
var rawtext = UrlFetchApp.fetch("https://kolayoto.com/collections/lastikleri.json").getContentText()
var jsonObj = JSON.parse(rawtext);
var contentObj = jsonObj.collection
var columns = Object.keys(contentObj)
var colName = []
var result = []
for (var i = 0; i < columns.length; i++){
var key = columns[i]
var value = contentObj[key]
result.push(value)
}
var numRow = 1
var numCol = columns.length
if(lastRow+1 == 1){
spreadsheet.getRange(lastRow+1, startCol, numRow, numCol).setValues([columns]);
spreadsheet.getRange(lastRow+2, startCol, numRow, numCol).setValues([result]);
}else {
spreadsheet.getRange(lastRow+1, startCol, numRow, numCol).setValues([result]);
}
spreadsheet.getRange(lastRow+1, startCol).activate();
};
The function that should take the Products Count number of the last row and send mail if it is less than 1000. (It is not working and has not been completed yet.) https://gyazo.com/e2fd5cdc4043dec00da1fce0e3c6c0ca (6562 is products count)
function SendEmail() {
// Fetch the monthly sales
var spreadsheet = SpreadsheetApp.getActiveSheet();
// I need your help in here. How can I get the products count in the last row after each run?
// Check totals sales
if (productsCount < 1000){
// Send Alert Email.
var message = 'KolayOto Lastik Ürün Sayısı Uyarısı!'; // Second column
var subject = 'Ürün sayısı uyarısı!';
MailApp.sendEmail("bbelcioglu#sekizgen.com", subject, message);
MailApp.sendEmail("berk.belcioglu#gmail.com", subject, message);
}
}
I hope I could explain the problems enough. I would be glad if you help.
Thanks.
I believe your goal as follows.
You want to retrieve the Products Count number from the URL using Google Apps Script.
In this case, you want to return the value of 6562.
You want to return that value at the function of _1().
For this, how about this answer?
Modification points:
When the returned value from the URL is seen, the Products Count number can be retrieved with contentObj.products_count.
Modified script:
When your script of _1() is modified, it becomes as follows.
From:
spreadsheet.getRange(lastRow+1, startCol).activate();
};
To:
spreadsheet.getRange(lastRow+1, startCol).activate();
return contentObj.products_count; // <--- Added
};
And, by above modification, SendEmail() can be modified as follows.
function SendEmail() {
var productsCount = _1(); // <--- Added
// Fetch the monthly sales
var spreadsheet = SpreadsheetApp.getActiveSheet();
// I need your help in here. How can I get the products count in the last row after each run?
// Check totals sales
if (productsCount < 1000){
// Send Alert Email.
var message = 'KolayOto Lastik Ürün Sayısı Uyarısı!'; // Second column
var subject = 'Ürün sayısı uyarısı!';
MailApp.sendEmail("bbelcioglu#sekizgen.com", subject, message);
MailApp.sendEmail("berk.belcioglu#gmail.com", subject, message);
}
}

Implementation of GoogleSheets Stock Price Email Alerts

I have a Googlesheets Stock Price Alert Script Running for a single stock in a GoogleSheet. It checks the current price against a target price and sends an email alert if it is lower.
How would I expand my script to check a list of stocks in the spreadsheet? I think I need a loop or something to scroll down each row but I'm unsure of how to do this.
My working code for single row check:
// Fetch the stock price
var stockNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A2");
var currentPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("C2");
var targetPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
var stockName = stockNameRange.getValue();
var currentPrice = currentPriceRange.getValue();
var targetPrice = targetPriceRange.getValue();
// Check stock prices
if (currentPrice < targetPrice){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = stockName +" "+ currentPrice +" is below your target price of "+ targetPrice;
var subject = 'Low Price Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}```
Try this:
function sdk(){
// Fetch the stock price
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1");
var data = ss.getRange("A13:C23").getValues(); // gets all the data from the three cols and puts it into a 2D array.
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("B2");
var emailAddress = emailRange.getValues();
var message = "";
for (var i = 0; i < data.length; i++){ // will go over the rows that you stored in data with data[i][0] being the stock name, data[i][1] being the target and data[i][2] being the current value.
// Check stock prices
if (data[i][2] < data[i][1]){
// Send Alert Email.
message += data[i][0] +" "+ data[i][2] +" is below your target price of "+ data[i][1] + " \n";
}
}
if (message != "")
MailApp.sendEmail(emailAddress, 'Low Price Alert', message);
}
Keep in mind that I used the range A13:C23 because that's where I had my test data, you will have to use yours depending on how you have structured your sheet, but this code will loop and get you the information you want into the email. it basically keeps appending rows of "alerts" into a message and sends everything together at the end of the loop.
When working with Apps Scripts, try to limit the calls to the APIs to make the code more optimized, this is why I changed the way you stored the ranges into a single call when getting the sheet in var ss = ..., this is also why using getValues() is important, it's only one call to the API instead of getting individual cells' values.

How to send conditional email alert on google sheet?

I'm setting up an email alert on my google sheet, in which if a value in one column goes below 2 I get an email alert on my mail.
I have mulitple domains and it is very tedious to check the domains expiry date every day. I created a sheet in which I put up domain name, registrar,hosted, todays date, expiry date, Expiry remaining days. Now I want to create an alert on "Expiry remaining days column", so that when the remaining days is below 2 days it send an alert email to my list of email addresses.
What I have already done is getting an email for one cell value but what I want to do is get it on whole column or number of column values.
function CheckSales() {
// Fetch the values
var domainexpireRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("domain list").getRange("F2");
var domainexpire = domainexpireRange.getValues();
// Check domain expiring
if ( domainexpire < 2){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Company emails").getRange("B2:B4");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = '2019 smtp Domain Expiring in two days. Please check the sheet domain sheet '; // Second column
var subject = '2019 smtp Domain Expiring';
MailApp.sendEmail(emailAddress, subject, message);
}
}
I have a sheet which has multiple rows and columns, what I want to do is check column F and if any of the value on column F is less than 2 then send an alert email to my email addresses.
My code is working fine if I copy paste the code to multiple times and change the "getRange("F2");" to F2,F3,....F100 .
But it is not good way to put up a code. Can anyone tell me if I can edit some code and get the result.
I tried using "getRange("F2:F");" & getRange("F2:F54");but it doesn't worked out.
Thanks for your help.
Try using a for statement to loop through the whole sheet, the one below should work:
function checkSales() {
// Fetch the values
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName("domain list");
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
// loop through each row starting at row 2
for (var i = 1; i < data.length; i++) {
var domainExpire = data[i][5];
// Check domain expiring
if (domainExpire < 2) {
var emailRange = spreadsheet.getSheetByName("Company emails").getRange("B2:B4");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = '2019 smtp Domain Expiring in two days. Please check the sheet domain sheet '; // Second column
var subject = '2019 smtp Domain Expiring';
MailApp.sendEmail(emailAddress, subject, message);
}
}
}
Try this:
function CheckSales() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('domain list');
var domainexpireRange=sh.getRange(1,6,sh.getLastRow()-1,1);
var domainexpire=domainexpireRange.getValues();
for(var i=0;i<domainexpire.length;i++) {
// Check domain expiring
if (domainexpire[i][5]<2){
var emailRange=ss.getSheetByName("Company emails").getRange("B2:B4");
var emailAddress=emailRange.getValues().map(function(r){return r[0];}).join(',');
// Send Alert Email.
var dateString=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy");
var message=Utilities.formatString('%s smtp Domain Expiring in two days. Please check the sheet domain sheet.',dateString);
var subject=Utilities.formatString('%s smtp Domain Expiring',dateString);
MailApp.sendEmail(emailAddress, subject, message);
}
}
}

GSheets- Automate reminder e-mail to client 1-2 days prior to appointment

I'm looking for a way (google app script, add-on, or otherwise) that will automate an appointment reminder e-mail using cell values in my google spreadsheet. Currently, my work flow is like this:
I fill out my client ID and appointment date google form.
Mail merge sends a confirmation e-mail to client that informs them of their appointment date and time.
I'd like for the 3rd step to be that an e-mail is automatically sent 1-2 days prior to the appointment date and maybe a 4th step to send the e-mail on the appointment date to remind them.
Here is my sheet with dummy data and without mail merge formatting:
Although I've looked on these forums and stack exchange, I cannot find a solution to my problem. I've found that people are trying to achieve similar, but mostly want e-mails routed to a static e-mail/e-mails. My needs are more dynamic. Please help.
Here's what what I'm working with:
function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow()-1; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)
for (i in data) {
var row = data[i];
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
//Logger.log(date);
var sheetDate = new Date(row[9]);
//Logger.log(sheetDate);
var Sdate = Utilities.formatDate(date,'GMT-0600','MM:dd:yyyy')
var SsheetDate = Utilities.formatDate(sheetDate,'GMT-0600', 'MM:dd:yyyy')
Logger.log(Sdate+' =? '+SsheetDate)
if (Sdate == SsheetDate){
var emailAddress = row[8]; // Patient Email
var message = row[6];row[7]; // Date and Time
var subject = "Your appointment is in 1 day!." +message;
MailApp.sendEmail(emailAddress, subject, message);
//Logger.log('SENT :'+emailAddress+' '+subject+' '+message)
}
}
}
What I've referred to and tried to make work for me:
Referencing by date/day- Google Forums:
Emails sent based on date- Google Forums:
Emails sent based on date - Stack Overflow:
Due Date Reminders - Stack Overflow
Create a calendar event with a default set of notifications
Here's a function that creates an event on your calendar with default notifications of 1 day, 2 days and 1 hour. You supply with an array that contains
Client Name, Appointment Date and Appointment Time as follows:
['Client Name','11/31/2017','1:30:00 PM']
function testCreateEventWithReminders()
{
createEventWithReminders(['Harry Dog','11/20/2017','1:30:00 PM'])
}
//eA=[clientName,date,time]
function createEventWithReminders(eA)
{
var minute=60*1000;
var hour=60*minute;
var day=24*hour;
var cal=CalendarApp.getCalendarById('CalendarID');//You need to supply your calendarID
var now=new Date().valueOf()
var start=new Date(eA[1] + ' ' + eA[2]);
var endValue=start.valueOf() + (hour);
var end=new Date(endValue);
var event=cal.createEvent(eA[0], start, end);
event.addEmailReminder(24*60);//reminders in minutes
event.addEmailReminder(2*24*60);
event.addEmailReminder(60);
}
Above you will need to insert your calendar ID. If you run displayCalendarInfo you should be able to determine what the calendar names and id's are.
function displayCalendarInfo()//Use this function to determine calendar names and ids.
{
var cals=CalendarApp.getAllCalendars();
var s='Calendar Information';
for(var i=0;i<cals.length;i++)
{
s+=Utilities.formatString('<br />Name: %s Id: %s', cals[i].getName(),cals[i].getId());
}
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var ui=HtmlService.createHtmlOutput(s).setWidth(1200).setHeight(450);
SpreadsheetApp.getUi().showModelessDialog(ui, 'Calendar Data');
}
If you want to create your own non default reminders you can add more elements to the input array
Additional Instructions:
The input to the function createEventWithReminders(eA) is an array in the form ['client name','mm/dd/yyyy','hh:mm:ss AM'] where the date and time are for the appointment.
I'm assuming that you can integrate this function into your spreadsheet some how. Personally, I would probably would have made it into a contained webapp because I like to use Siri to do a lot of my data entry thus eliminating the need to type on my mobile device and providing me the opportunity to enter reminders as I proceed through the day without my laptop.