How to send conditional email alert on google sheet? - google-apps-script

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);
}
}
}

Related

I'm trying to use paypal IPN with Google Sheets and Gmail to set up an automated email response when a buyer purchases a digital download but too hard

I've been successful getting the paypal ipn data to my google sheets using a variation of a script i found online.
function doPost(e) {
var rowData = [];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
rowData.push(new Date(e.parameter.payment_date));
rowData.push(e.parameter.payment_type);
rowData.push(e.parameter.payment_status);
rowData.push(e.parameter.payer_email);
rowData.push(e.parameter.item_name1);
rowData.push(e.parameter.item_number1);
rowData.push(e.parameter.quantity);
rowData.push(e.parameter.first_name);
rowData.push(e.parameter.last_name);
rowData.push(e.parameter.address_street);
rowData.push(e.parameter.address_city);
rowData.push(e.parameter.address_state);
rowData.push(e.parameter.address_zip);
sheet.appendRow(rowData);
}
The above seems to work great and what the next step and I'm trying to do is take the data from a few of the cells in my google sheet where this script is working and use that in another script where an email with a link or attachment to the digital download images they purchased. I need to extract the first name, last name, payer email, and a variation of the itemname1 from above function and send the email automatically. I've set up the google sheet with the IPN information above and have added a last column 'P' where the link to the image will be located online using data from itemname1 as mentioned. The next step would be to use something like the function below using my data, but I'm having a super difficult time. I need to tweak the below function to work with my data. Is that possible? I'm not having any luck and it's all so close at this point. Anyone out there now how to do this? Can you point me in the right direction?
Something like this is what I was thinking would work for me, but I'm not sure how to tweak it to do the job I need:
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
var subject = 'Sending emails from a Spreadsheet';
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
My problem is that I haven't been able to put all the data together and make it work yet. Any help?

how do i send an email with info from a row with criteria from one of its column using google app script

I want to write a script that will send an email based on the criteria of a single column.
This is for an inventory management system that will send emails to remind that certain items are low in count.
eg.
if row 5's column J is = "reminder", send values of row 5's column B and C to my email. (col B and C is item description and quantity count respectively)
I just started learning about google app script so I'm not sure how to write it myself, but from other forum posts, this is what I got.
var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
values.forEach(function(row) {
var indent = row[10]; //column j
if (indent !== '') {
var EditedRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("store list").getRange(indent);
var Edited = EditedRange.getValue();
}
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mail").getRange("B2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = Edited;
var subject = 'For Action: Indent' ;
MailApp.sendEmail(emailAddress, subject, message);
});
}
I split the code up and tested emailing and apparently the email portion of the codes work, but it is the retrieving of data that is not working and I don't really know how to get it working.
To get started, have a look at the Apps Script reference
There you will see that to retrieve the value of a single cell it is bets to use the method getValue() instead of getValues()
You need to specify the range (cell) wrom ehre you want to get the value
The easiest way to do so is with the method getRange() specifying A1 notation
A simple sample would be:
var sheet = SpreadsheetApp.getActiveSheet();
var checkValue = sheet.getRange("J5").getValue();
if (checkValue == "reminder"){
var B5Value = sheet.getRange("B5").getValue();
var C5Value = sheet.getRange("C5").getValue();
var message = B5Value + " and " + C5Value;
var emailAddress = "you need to define the email address of the recipient either in the code or a cell of the sheet";
var subject = "Define here your subject";
MailApp.sendEmail(emailAddress, subject, message);
}
Please make sure to dedicate enough time to study the Apps Script documentation to understand this code and be able to troubleshoot and perform simple modifications.

Set a cell value after sending an email according to the volunteer application status

I'm in creating a volunteer registration system for the organization I work with. I want to write a script so that any time I run the script from the dropdown menu, it scans the spreadsheet row by row, and determines what the application status is. If the status is open, I want it to then determine if the status open email has been sent, if it hasn't, send the email, and change the value of the open_email value for that row to "SENT". If the app status is closed, I want it to do the same thing for the closed email.
Volunteer Spreadsheet
Basically, I want to run this function whenever we get new volunteer applications so that they receive emails based on their application status.
I've been successful in writing the function to scan the rows and send the emails based on the application status, but I can't seem to figure out how to get it to change the value of the cell after it has sent the corresponding email.
Here is the code for the mail merge function:
//function for menu item 1
function volunteerMailMerge() {
SpreadsheetApp.getUi();
//references
var ss = SpreadsheetApp.openById("1Ei86oBsafBc6GdFeKFFGdbljyUzbWRFRF8eWvnoYdIU");
var sheet = ss.getSheetByName("Application Status");
var range = sheet.getDataRange(); //sets range to all data in the spreadsheet
var values = sheet.getDataRange().getValues(); //translates the range into values in an array
var headers = values.shift(); //removes headers from values array
//loop through rows
for (var i = 0; i < values.length; i++) {
var firstName = values[i][0];
var lastName = values[i][1];
var email = values[i][2];
var position = values[i][3];
var status = values[i][4];
//mailmerge
if (status == "OPEN" && openEmail == "") {
//if app status is open, and openEmail hasn't been sent, do this
GmailApp.sendEmail(email, "SAFE Volunteer Application",{
htmlBody: "email body",
});
//change value of column 5 on the current row
} else {};
};
}
To change a Google Sheet cell value use setValue(value)
Sets the value of the range. The value can be numeric, string, boolean
or date. If it begins with '=' it is interpreted as a formula.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("B2");
cell.setValue(100);

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.

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);
}