Monday, October 24, 2011

Google Docs spreadsheet automatic email sending


This script sends an email using google docs spreadsheets.
Here is a script I made that sends an email to people if a cell doesn't say email sent. It uses cells that exist to put together the body and subject of the email. You can do alot more with this but its good enough to work.


function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 10000;   // Number of rows to process
  // Fetch the range of cells A2:N10000
  var dataRange = sheet.getRange(startRow, 1, numRows, 14)
  // 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[6];  // First column
    var message = row[12];       // Second column
    var emailSent = row[13];     // Third column
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      if(emailAddress.length == 0){
        //sheet.getRange(startRow + i, 15).setValue("stop");
        break;
      }
      var subject = "Sending emails from a Spreadsheet";
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 14).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

2 comments:

sam said...

can you explain what this code is doing?
Thanks

sam said...

can you explain what this code is doing?
Thanks