r/GoogleAppsScript • • Sep 14 '20

Question Need help with an email script!

Hello all!

This is my first time putting together a script and I've been able to do as much as my knowledge and Google searching has allowed. If anyone can help, I would greatly appreciate it!

The goal of this script is use a Google sheet and automatically send emails to students reminding them of the assignments they are missing. I have been able to set up the email template and enable cc'ing the email to parents, but I can't figure out a few other things. Here is a sample sheet.

function sendEmail() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = sheet.getSheetByName('Sheet1');
  var sheet2 = sheet.getSheetByName('Sheet2');
  var numColumns = sheet1.getLastColumn();

  var subject = sheet2.getRange(2,1).getValue();
  var n = sheet1.getLastRow();
  for (var i = 2; i < n+1 ; i++ ) {
    var emailAddress = sheet1.getRange(i,3).getValue();
    var name = sheet1.getRange(i,1).getValue();
    var assignment = sheet1.getRange(i,5).getValue();
    var message = sheet2.getRange(2,2).getValue();
    var parentAddress = sheet1.getRange(i,4).getValue();

    message=message.replace("<name>",name).replace("<assignment 1>",assignment);
    
    MailApp.sendEmail(emailAddress, subject, message,
                      {cc: parentAddress});
  }
}

There are the 3 things I need help with:

  1. The contents of the cells under the different assignments are irrelevant; I only need to indicate if something is completed or not. In my template email, Assignment 1 gets replaced with X, since it is the contents of the cell. In this case, the X denotes the assignment is completed. What I really want is to check if a cell is empty, and then the assignment/column name will be added into the body of the email with any other assignments that have no contents in the appropriate cell.

  2. How can I set a condition where if a student has every assignment completed (none of the cells are empty), then an email will not be sent?

  3. How can the number of columns/assignments be dynamic? I want to be able to add new assignments/columns without jeopardizing the script. I've included getLastColumn(); but I am not sure how to actually use it.

Thank you!

6 Upvotes

12 comments sorted by

View all comments

Show parent comments

1

u/DoctorMeatBoy Sep 14 '20

Arrays are the reason I stopped pursuing any sort of coding years ago. I just couldn't figure it out! But that would awesome, thank you!

2

u/lordph8 Sep 15 '20

Alright, I completely rewrote it to how I would do it with explanations. This should help you figure it out in addition to some of the other comments on this thread.

Loops and arrays give you dynaism, and if you want to accomplish some real things you will have to use them in conjunction with if statements.

function sendEmail() {
  var ss = SpreadsheetApp.getActive();
  var sheet1 = ss.getSheetByName('Sheet1');
  
  //var subject = sheet2.getRange(2,1).getValue() > It is easy enough to write in the subject like below.
  var subject = "Missing Work";
  //var n = sheet1.getLastRow(); > as mentioned in another comment it is quicker and better to use .getDataRange().getValues() to get a 2D array to work from,
  var data = sheet1.getDataRange().getValues();
  
  //Arrays start at 0 and it is just the data from the sheet. It is represented for an easy way to undestand this data[row][column]. So as an example 
  //data[0][0] would be selecting the data in cell A1.
  
  //loops are just a counter that counts from a number to just below another number (if you use the conventional < for the second condition). So to make this dynamic
  //I will look at your title row for after column D for your "assignments" if you fill the in the title with an assignment name it will know to look for the 
  //corrisponding cell for an X.
  
  //for (var i = 2; i < n+1 ; i++ ) {
  for (i = 1; i < data.length; i++) {
    //i will count from 1 (row 2) to the end of the sheet.
    var assArr = [];
    //create a blank array;
    var name = data[i][0] + " " + data[i][1];
    //first name + a space + last name
    var emailAddress = data[i][2];
    var parentAddress = data[i][3];
    
    //I would rewrite the message here in HTML, additionally I will add the assignment names to the array with another loop.
    for (x = 4; x < data[0].length; x++) {
      //4 to start at column 5 (assignment 1), 0 to represent the title row (row 1) and length to represent the last column number in that row. This way it will 
      //look for X's under under columns where you have assignment named. (if you have blank spaces between assignments in the title row, this will break).
      
      if (data[i][x].toUpperCase() != "X" && data[0][x] != "") {
        //i for the current row, x for the current column between col 5 and the end of the sheet. toUpperCase() to turn x into X if you put in a lowercase x && is and.
        //!= means is not. So if data in cell is not X and the title col is not blank (uneccisary).
        
        assArr.push("<li>" + data[0][x] + "</li>");
        //add the title cell name to an array with HTML for list item. This will make sense in our email.
        
      }    
      
    }

    //message=message.replace("<name>",name).replace("<assignment 1>",assignment);
    
    var message = "<p>Hello " + name + ",</p>" +

                   "<p>I am currently missing the following assignments from you. For specific assignment details, please refer to Schoology.</p>" + 
                     
                   "<ul>" + assArr.join("") + "</ul>" +
                     
                   "<p>Please email back with any questions or concerns,<br>Ms. Teacher"
                   
                   //name is defined above, p = paragraph, ul = unordered list, with the above array jointed together. br = break
                   
     if (assArr.length > 0) {
       //It will only send the email if a missing assignment has been added to the array.

    MailApp.sendEmail({
          to: emailAddress,
          cc: parentAddress,
          subject: subject,
          htmlBody: message
          
        })
    
     }
  }
}

1

u/DoctorMeatBoy Sep 15 '20

This works exactly how I was envisioning. And the line-by-line comments really helped me grasp what you were doing. Where were you when I was trying to learn to code in high school?! Thanks for all of your help!

1

u/lordph8 Sep 15 '20

Stuff is complicated, but not that complicated. It's fairly easy to understand with practical explanation. A lot of education try to instill a rudimentary base of knowledge, but seeing how it all works together takes time and effort and some don't get there. This stuff is really just the tip of the iceberg, even within the world of google script and google APIs.