Automatically Email Col3 When Col10 to Col12 are Updated (Google Sheets) - email

Afternoon!
I'm attempting to write a script that automatically sends an email of the value in Col3 when the corresponding value (same row) in Columns 10 to 12 are edited. Ideally, it would not send an email in regards to Col11 or Col12 if Col10 is already filled, but that would be icing on the cake. Attached is the script I was originally trying to build off of (ripped from a google search) - however, I don't need a customizable email body, just the value of Col3.
function sendEmailByRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row,1,row,4).getValues();
var row_values = values[0];
var mail = composeApprovedEmail(row_values);
//Uncomment this line for testing
//SpreadsheetApp.getUi().alert(" subject is "+mail.subject+"\n message "+mail.message);
MailApp.sendEmail(admin_email,mail.subject,mail.message);
var candidate_email = composeCandidateEmail(row_values);
MailApp.sendEmail(candidate_email.email,candidate_email.subject,candidate_email.message);
}
function composeCandidateEmail(row_values)
{
var first_name = row_values[0];
var last_name = row_values[1];
var email = row_values[2];
var message = "The following applicant is approved: "+first_name+" "+last_name+
" email "+email;
var subject = first_name+ ", Your appliation is approved";
var message = "Hello "+first_name+"\n"+
"Your application is approved.\n Please follow the following instructions to proceed with the process.\n";
//... etc
return({message:message,subject:subject, email:email });
}
Thanks

Related

Create mailing list for sendmail

I would like to create a list of emails, which are listed in the column of a sheets.
how can I do this?
example:
column A
email 1
email 2
email 3
mailling = column A
MailApp.sendEmail({
to: mailling,
subject: "test",
body: "Test message",
if your emails are in column A starting from row 2:
function getEmails() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const emails = sh.getRange(2,1,sh.getLastRow() - 1, 1).getValues().flat();
return emails.join(',');
}
function sendEmails() {
MailApp.sendEmail({to: getEmails(),subject: "test",body: "Test message"});
}
I think you should check the documentation of the class like suggested in the comments, it has really good features that can improve the way you email. Anyway, here is an example that can help you.
function sendMail() {
//Each numer means the column of the sheets thats going to grab the value
var first = 0;
var second = 1;
var third = 2;
//In the Column D must have the emails
var fourth =3;
//Specifies the HTML document that going to give the structure of the email
var emailTemp = HtmlService.createTemplateFromFile("email");
//Tells wich is the sheet to take information
//in this case the sheets name is "Data Base"
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data Base");
//Gives the range of the columns that the information is going to be
var data = ws.getRange("A1:E" + ws.getLastRow()).getValues();
//This is an optional filter in the Column F so you can filter wich rows to run
data = data.filter(function(r){ return r[5] == true });
//To use the variables in between the HTML file your going to use the value after "emailTemp." as <?= fr ?>
data.forEach(function(row){
emailTemp.fr = row[first];
emailTemp.se = row[second];
emailTemp.th = row[third];
var htmlMessage = emailTemp.evaluate().getContent();
GmailApp.sendEmail(row[fourth], "HEEERE GOES THE SUBJECT OF THE EMAIL", "Your email doesn't support HTML.", {name: "Email", htmlBody: htmlMessage})
});
Here I used a html template to send emails with variables extracted from other columns. You can check out this github

E-mail notification based on cell value. Unable to apply script function for all rows

I am using Google sheets and the Google script editor to create a script to automatically send myself an e-mail every time a product quantity goes below the minimum inventory level. Since I have multiple products with different minimum inventory levels I expect to get a series of e-mails, one for each row.
I use one sheet for the actual Inventory data and another sheet that contains information for the script to refer to, such as my email and what message to include in the e-mail.
I succeeded having an e-mail sent collecting data from the first row of the Inventory sheet but I am not being able to apply that for all the following rows.
I tried changing the .getRange("F2") to .getRange("F2:F"), then whenever one of the products goes under the minimum inventory level I get one single e-mail containing the information about all products, regardless of whether their quantity is under the minimum level or not.
The ideal solution would be ONE single e-mail containing all the information about all products that are under the minimum quantity .
Here is a link to my spreadsheet: https://docs.google.com/spreadsheets/d/1ZHmBvi8ZeaDRYq6Qigaw08NUiOwZumPrLnvnka_mgmA/edit?usp=sharing
Current script:
function CheckInventory() {
// Fetch inventory quantity
var InventoryRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory").getRange("F2");
var Inventory = InventoryRange.getValue();
// Fetch minimum quantity
var MinimumQuantityRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory").getRange("D2");
var MinimumQuantity = MinimumQuantityRange.getValue();
// Check Inventory
if (Inventory < MinimumQuantity){
// Fetch email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("E2");
var emailAddress = emailRange.getValues();
// Fetch email message details.
var detailsRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("G2");
var details = detailsRange.getValues();
var subjectdetailsRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("H2");
var subjectdetails = subjectdetailsRange.getValues();
// Send Alert Email.
var message = details;
var subject = subjectdetails;
MailApp.sendEmail(emailAddress, subject, message);
}
}
Update:
As you said in a comment, you want the email to be sent when you edit an inventory cell, and only if this edited inventory quantity is below the corresponding minimum. So here I update my answer accordingly.
First, I guess you have done this already, but because the function uses sendEmail, you will have to grant authorization for it to work. I created a trigger for that. Run this once:
function createEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger("CheckInventory")
.forSpreadsheet(ss)
.onEdit()
.create();
}
Then, this is the function that will run every time the spreadsheet is edited. To avoid the email to be sent every time the file is edited, we need a condition that checks whether the edited cell is an inventory and that this inventory is below the minimum:
function CheckInventory(e) {
var ss = e.source;
var inventorySheet = ss.getSheetByName("Inventory");
var rowIndex = e.range.getRow();
var columnIndex = e.range.getColumn();
var numCols = 6;
var row = inventorySheet.getRange(rowIndex, 1, 1, numCols).getValues()[0];
var editedInventory = row[5];
var editedMinimum = row[3];
var sheetName = ss.getActiveSheet().getName();
// Checking that: (1) edited cell is an inventory quantity, and (2) Inventory is below minimum
if(editedInventory <= editedMinimum && sheetName == "Inventory" && columnIndex == 6 && rowIndex > 1) {
var inventoryValues = inventorySheet.getDataRange().getValues();
var emailBody = "";
for(var i = 1; i < inventoryValues.length; i++) {
var inventory = inventoryValues[i][5];
var minimum = inventoryValues[i][3];
if(inventory <= minimum) {
var productName = inventoryValues[i][0] + " " + inventoryValues[i][1];
var productUnits = minimum + " " + inventoryValues[i][4];
var messagePart1 = "Inventory for " + productName + " has gone under " + productUnits + ". ";
var messagePart2 = "Organise purchase order. Inventory as of today is: " + inventory + " " + inventoryValues[i][4];
var message = messagePart1.concat(messagePart2);
var newItem = "<p>".concat(message, "</p>");
emailBody += newItem;
}
}
var emailSubject = "Low inventory alert";
var emailAddress = "your-email#your-domain.com";
// Send Alert Email
if(emailBody != "") {
MailApp.sendEmail({
to: emailAddress,
subject: emailSubject,
htmlBody: emailBody
});
}
}
}
As I said in a comment, if you just want to send an email, it doesn't make sense to have many email subjects, so I hardcoded the subject.
Regarding the emails, I assumed you just want an email address to receive the email, so I hardcoded it too. If you want all the different email addresses found in Notifications tab to receive emails regarding all products, a small fix would be needed to this code. Tell me if that's needed for you.
Also, I didn't use your notifications tab at all, I created the message directly using the script. I'm not sure it is that useful to have the sheet "Notification Rules". Much of its info is the same as the one in inventory, and the rest of data (email address, basically) could be easily included there. But whatever suits you.
I hope this is of any help.

Script for Google sheets (auto email function)

Google Sheets Script
I need to generate an auto email reply when Column "A" is marked "Completed". The email address to send this to is in Column "I" and subject of the email needs to be data in Column "H" while the body of the email will be generic for all emails sent. This is all specific to each Row.
I have multiple scripts running, for hiding rows etc, but nothing this complex.
All data is sent in to spreadsheet from Google Forms, and will need to encompass all rows
Any help would be much appreciated.
I created a script for something similar to this, except it runs off of check boxes. You could easily edit this code to have the email recipient variable to point to a value in a column by adding a .getdisplayvalue
How I used it is basically just as a script trigger, so I wouldn't have it replace the "progress" column you have, but to add a column for them to check when they're done editing the row.
Side Note: This script purposefully sets the check box back to default after clicking "yes I want to send the email" on the alert, otherwise the script would continuously run.
Without seeing your Google Sheet or current code/this code inserted, I wouldn't be able to help you implement at all. Let me know if this helps.
/*
A function to:
* After clicking a checkbox, auto prompt a yes/no box
* Upon "yes", copies that row from the source sheet to a destination sheet
* send an e-mail based on that new row's data
I reccomend protecting the response sheet and hiding it, as well as protecting the check box column to give edit access to only those you want to be able to send e-mails.
NOTES:
*It is important that the headers on your source sheet match your destination sheet.
* You have to run the script from the editor first to accept permissions for the emailapp and driveapp
* you need to set up a project trigger (edit/current project triggers) for the source sheet, on spreadsheet, on edit.
*The email will come from the owner of the google sheet and owner of the script project. (the person who reviews and accepts permissions)
MAKE SURE you are the owner of the sheet, that you are putting the code into the editor, and that you're okay with the e-mail coming from and replying to your email address.
*/
function EmailNotification(e) {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Assets'); //source sheet
var columnb = sheet.getRange('B:B'); //Column with check boxes
var columnbvalue = columnb.getValues();
var notifysheet = ss.getSheetByName('Responses'); //destination sheet
var data = [];
var rownum =[];
//Condition check in B:B (or check box column); If true copy the same row to data array
for (i=0; i<columnbvalue.length;i++) {
if (columnbvalue[i] == 'true') {
var columnb2 = sheet.getRange('B2:B');
columnb2.setValue('false');
// What you want to say in the pop up alert
var response = ui.alert('Hold Up!\n Are you sure you want to send an email to finance for this asset change?', ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
data.push.apply(data,sheet.getRange(i+1,1,1,20).getValues());
//Copy matched ROW numbers to rownum
rownum.push(i);
//Copy data array to destination sheet
notifysheet.getRange(notifysheet.getLastRow()+1,1,data.length,data[0].length).setValues(data);
var activeRow = notifysheet.getLastRow();
var assetname = notifysheet.getRange(activeRow, 1).getDisplayValue(); // The number is the column number in the destination "responses" sheet that you want to include in the email
var owner = notifysheet.getRange(activeRow, 3).getDisplayValue();
var serial = notifysheet.getRange(activeRow, 9).getDisplayValue();
var podate = notifysheet.getRange(activeRow, 6).getDisplayValue();
var email = 'theiremail#gmail.com' //The email address in which you want to send the email notification to
var subject = 'Asset has changed department ownership!'
//Body of the email message, using HTML and the variables from above
var message =
'<br><br><div style="margin-left:40px;">Heads Up!</div>'
+'<br><br><div style="margin-left:40px;">An asset has changed department ownership.</div>'
+'<br><br><div style="margin-left:40px;"><h3 style="text-decoration: underline;">Asset Name:'+ assetname +'</h3></div>'
+'<div style="margin-left:40px;">New Departmet Owner: '+ owner +'</div><br>'
+'<div style="margin-left:40px;">Serial: '+ serial +'</div>'
+'<div style="margin-left:40px;">Purchase Date: '+ podate +'</div>'
+ '<br><br><div style="margin-left:40px;">ヽ(⌐■_■)ノ♪♬</div>';
MailApp.sendEmail(
email,
subject,
"",
{
htmlBody: message,
name: 'Sadie Stevens', //The name you want to email coming from. This will be in bold, while your e-mail address will be small in italics
});
}
}
}
}
Try it this:
function EmailNotification(e) {
var ui=SpreadsheetApp.getUi();
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet=ss.getSheetByName('Assets');
var columnb=sheet.getRange(1,2,sheet.getLastRow());
var columnbvalue=columnb.getValues();
var notifysheet=ss.getSheetByName('Responses');
var data=[];
var rownum=[];
for (var i=0;i<columnbvalue.length;i++) {
if (columnbvalue[i] == 'true') {
var columnb2=sheet.getRange(2,2,sheet.getLastRow()-1);
columnb2.setValue('false');
var response=ui.alert('Hold Up!\n Are you sure you want to send an email to finance for this asset change?', ui.ButtonSet.YES_NO);
if (response==ui.Button.YES) {
data.push(sheet.getRange(i+1,1,1,20).getValues());
rownum.push(i);
notifysheet.getRange(notifysheet.getLastRow()+1,1,data.length,data[0].length).setValues(data);
var activeRow=notifysheet.getLastRow();
var assetname=notifysheet.getRange(activeRow, 1).getDisplayValue(); // The number is the column number in the destination "responses" sheet that you want to include in the email
var owner=notifysheet.getRange(activeRow, 3).getDisplayValue();
var serial=notifysheet.getRange(activeRow, 9).getDisplayValue();
var podate=notifysheet.getRange(activeRow, 6).getDisplayValue();
var email='theiremail#gmail.com' //The email address in which you want to send the email notification to
var subject='Asset has changed department ownership!'
var message =
'<br><br><div style="margin-left:40px;">Heads Up!</div>'
+'<br><br><div style="margin-left:40px;">An asset has changed department ownership.</div>'
+'<br><br><div style="margin-left:40px;"><h3 style="text-decoration: underline;">Asset Name:'+ assetname +'</h3></div>'
+'<div style="margin-left:40px;">New Departmet Owner: '+ owner +'</div><br>'
+'<div style="margin-left:40px;">Serial: '+ serial +'</div>'
+'<div style="margin-left:40px;">Purchase Date: '+ podate +'</div>'
+ '<br><br><div style="margin-left:40px;">ヽ(⌐■_■)ノ♪♬</div>';
MailApp.sendEmail(email,subject,"",{htmlBody: message,name: 'Sadie Stevens'});
}
}
}
}

Google script: email with answers given by a single user to a form compiled in google drive

I've created a form using google drive.
In order to provide to answerers a summary of what they wrote I would like to send an email to each of them, using the email they insert in the form.
I think it is possible to do this installing a script in the spreadsheet of the form result that send an email every time a new row is recorded.
I've found (on this forum) the following script that is, unfortunately, an email alert with a modify in a certain spreadsheet.
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = "me#gmail.com";
var message = '';
if(cell.indexOf('G')!=-1){
message = sheet.getRange('D'+ sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'Update to '+sheet.getName();
var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellvalue + '». For message: «' + message + '»';
MailApp.sendEmail(recipients, subject, body);
};
And here is the help I need. The script sends an email to a single predefined address. Is it possible to let the script take the recipient email from a certain cell in the relevant row (for example the email is recorded in the col C of the spreadsheet) and send him a message that contains some text taken by other cells of the same row ( for example col D and E)?
Using the variables you defined in your code (sheet, row):
//returns email address in column C
var recipient = sheet.getRange(row, 3).getValue();
//returns values in column D and E
var info1 = sheet.getRange(row, 4).getValue();
var info2 = sheet.getRange(row, 5).getValue();
Please be aware that this is an 'expensive' way to get the values and you would better served getting all values as an array in one call and then referencing them by index, as below.
//get all required values in one call
var values = sheet.getRange(row, 3, 1, 3).getValues();
//define variables using array index
var recipients = values[0];
var info1 = values[1];
var info2 = values[2];

Programming google app script to trigger at a specific time by displaying spreadsheet in email body

I'm sending a spreadsheet in the body of an email everyday. I completed the email portion, but now im trying to program the trigger to set off at 1:15pm everyday. I'm not sure how to implement the code to trigger with the email?
'function nearMinute(minute) {
var sendRead = ScriptApp.newTrigger("sendRead1pm")
.timeBased()
.atHour(13)
.everyDays(1) // Frequency is required if you are using atHour() or atMinute()
.create();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Totals");
var subjecttable = UrlFetchApp.fetch("https://docs.google.com/spreadsheet/pub?
key=XXXXXXXXXXXXXXXXXXXXXXXXXXX=true&gid=1&output=html");
var htmltable = subjecttable.getContentText();
var fromName = "DoNotReply - email";
var rowData = ss.getRange("B16").getValues()[0];
var emailAddress = "emailaddress#gmail.com"; // First column
var message = {htmlBody: htmltable, name: fromName}; // Second column
var subject = "TEST $" + rowData;
MailApp.sendEmail(emailAddress, subject, "", message);
}`
You don't have to code your trigger. Make your function to do the email part and set up the trigger manually. In your script, go to Resources --> Current Project's Triggers and then add a trigger. This is the easiest.