Get Notified about Google Spreadsheet Changes | Google Apps script!

September 9, 2024 | 2 minutes read


Editorial Team

blog-image

AppSScript Code

        function sendEmailOnEdit(e) {
          if (!e) return; // add this line to check if "e" is undefined

          var sheet = e.source.getActiveSheet();
          var sheetName = sheet.getName();
          var recipients = "sharma.mohit@outrightcrm.com";
          var subject = "Someone Edited a Google Sheet";
          var body = "The Google Sheet named '" + sheetName + "' was edited.<br><br>";
          
          // Get the user who made the edit
          var user = Session.getActiveUser().getEmail();
          
          // Get the range of the edited cell
          var range = e.range;
          var row = range.getRow();
          var column = range.getColumn();
          
          // Get the new value of the edited cell
          var newValue = e.value;
          
          // Construct the table header
          var header = "<table style='border-collapse: collapse;'><tr><th style='border: 1px solid black; padding: 5px;'>User</th><th style='border: 1px solid black; padding: 5px;'>Row</th><th style='border: 1px solid black; padding: 5px;'>Column</th><th style='border: 1px solid black; padding: 5px;'>Value</th><th style='border: 1px solid black; padding: 5px;'>Date/Time</th></tr>";
          
          // Construct the table row
          var row = "<tr><td style='border: 1px solid black; padding: 5px;'>" + user + "</td><td style='border: 1px solid black; padding: 5px;'>" + row + "</td><td style='border: 1px solid black; padding: 5px;'>" + column + "</td><td style='border: 1px solid black; padding: 5px;'>" + newValue + "</td><td style='border: 1px solid black; padding: 5px;'>" + new Date().toLocaleString() + "</td></tr>";
          
          // Close the table
          var footer = "</table>";
          
          // Combine the header, row, and footer to create the body of the email
          body += "The following change was made to the sheet:<br><br>" + header + row + footer;
          
          // Send the email
          MailApp.sendEmail(recipients, subject, "", {htmlBody: body});
        }