-
Notifications
You must be signed in to change notification settings - Fork 1
/
How to Send Email Notifications for New Rows in Google Sheets Using Apps Script
70 lines (56 loc) · 2.16 KB
/
How to Send Email Notifications for New Rows in Google Sheets Using Apps Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function onChange(e) {
var sheetName = "NewEntries";
var sheet = e.source.getSheetByName(sheetName);
if (!sheet) {
Logger.log("Sheet not found: " + sheetName);
return;
}
var currentRowCount = sheet.getLastRow();
var properties = PropertiesService.getScriptProperties();
var lastRowCount = properties.getProperty('lastRowCount');
// If the last row count is not set, initialize it
if (!lastRowCount) {
properties.setProperty('lastRowCount', currentRowCount);
return;
}
lastRowCount = parseInt(lastRowCount);
// Check if a new row was added
if (currentRowCount > lastRowCount) {
var newRowRange = sheet.getRange(currentRowCount, 1, 1, sheet.getLastColumn());
var newRowValues = newRowRange.getValues()[0];
Logger.log("New row added: " + newRowValues);
// Send email notification
sendEmailNotification(sheet, newRowValues);
} else {
Logger.log("Edit did not add a new row or was not on the target sheet.");
}
// Update the stored row count
properties.setProperty('lastRowCount', currentRowCount);
}
function sendEmailNotification(sheet, newRowValues) {
var emailAddress = Session.getActiveUser().getEmail();
var subject = "New Row Added to " + sheet.getName();
var message = "A new row has been added to the sheet " + sheet.getName() + ":\n\n";
newRowValues.forEach(function(cellValue, index) {
var columnName = sheet.getRange(1, index + 1).getValue();
message += columnName + ": " + cellValue + "\n";
});
MailApp.sendEmail(emailAddress, subject, message);
Logger.log("Email sent to: " + emailAddress);
}
function testEmailNotification() {
var sheetName = "NewEntries";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
if (!sheet) {
Logger.log("Sheet not found: " + sheetName);
return;
}
// Simulate the new row values
var emailAddress = Session.getActiveUser().getEmail();
var newRowValues = ["Test Name", emailAddress , "Thu, Jun 6, 2024"];
// Log the simulated new row
Logger.log("Simulated new row: " + newRowValues);
// Send email notification with the simulated new row
sendEmailNotification(sheet, newRowValues);
}