Skip to main content

Conditional Google Spreadsheet App Script that automatically sends email based on the value of a cell

I'm just putting up here how I made a project which requires to make a Google App Script on a Google Spreadsheet to send email if a particular cell contains Yes or No or something like OK as a value of a cell or your column indicator for something.

It's like this, supposed you have a Google Form which has name, email, address, and other important details on it, and you also have there an input which asks the users who fill up the form if they want to receive an email or not? or something complex and customized that requires you to build a custom script on it and you can't find any add-ons available.

On the project I made, it required me to send an email if the value of a particular cell which is a computed value of some cells from another sheet is "Y" and also if "N", but the two has a different email body customized for the users based on their answer in the form. I broke the work down to pieces to learn about the scripting, first I studied how the email is sent using the script, so I found a tutorial from the Google Developers site (Yeah what's nice about Google is that it has a broad sources of documentation not just on their site but a also a lot from the developers community)

So go to your Google Drive and make a spreadsheet there with two columns 3 rows, the first row should be your header, and the 2nd and 3rd contains the data.

Like this:


Here's the simple code:
function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 2)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "Sending emails from a Spreadsheet";
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
So, while developing to complete the requirements, I have encountered some problems which needs to be addressed, not just one but a bunch of them:

1. Tag rows as sent to avoid resending the email again everytime the script runs.

2. How do we check a cell value to be used as a condition to implement a rule to on when to send the email.

3. If the spreadsheet contains more than 1 sheet and the sheet you're working with is not active, the script might encounter error, so we must do something about it on how we can make a particular sheet active.

4. The example above shows gives us a fix variable for rows, so how about if we want to get all the rows filled and loop with it?

5. Add or embed an image attachment in the email from a URL.

6. An extra problem encountered that I was able to solve was an addition of variables in app script, instead of adding the two values, the script is actually concatenating it, like variable x value is 2 and y is 0, the answer becomes 20? (Anyway let's just be careful in copy-pasting from tutorials because that's where the problem is in my experience)

That's pretty much the hurdles on our requirements and we can now build it perfectly. So far, the code above works just fine, we'll just be tweaking that a little bit more.

Here's the final code, I'll be explaining it in another article:

 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
71
72
73
74
75
function sendEmails() {
  
  var LogoUrl = "https://yourwebsite.com/photo.jpg";
  
  var LogoBlob = UrlFetchApp
                          .fetch(LogoUrl)
                          .getBlob()
                          .setName("LogoBlobName");
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
  
  var sheet = SpreadsheetApp.getActiveSheet();
  
  var startRow = 2;
  var numCol = 39;
  
  //get number of rows to process - 1 for header  
  var numRows = sheet.getLastRow();
  
  var EMAIL_SENTY = "Yes";
  
  var messageY = "This is the templated message number 1";
  var messageN = "This is the templated message number 2";
  
  var subject = "This is the email subject";
  var footer = "Something in the footer,<br>Signature";
  
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, numCol);
  
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  
  for (i=0;i<data.length;i++) {
    
    var row = data[i];
    var emailAddress = row[5];
    var highRisk = row[6];
    var emailSent = row[38];
    
    //check if email address is not blank to avoid error
    if(emailAddress!="" && emailSent!="Yes"){
      
      //high risk
      if(highRisk=="Y"){
        MailApp.sendEmail({
          to: emailAddress,
          subject: subject,
          htmlBody: messageY+"<br><br><h3><b>"+footer+"</b></h2><img src='cid:LogoBlobName'>",
          inlineImages:
          {
          Logo: LogoBlob
        }
                          });
        sheet.getRange(startRow + i, 39).setValue(EMAIL_SENTY);
      }
      
      //not high risk
      else{
        MailApp.sendEmail({
          to: emailAddress,
          subject: subject,
          htmlBody: messageN+"<h2><b>"+footer+"</b></h2><img src='cid:LogoBlobName'>",
          inlineImages:
          {
          Logo: LogoBlob
        }
                          });
        sheet.getRange(startRow + i, 39).setValue(EMAIL_SENTY);
      }
    }
    
  }
}

Comments

Popular posts from this blog

Reaction Paper for the movie The Count of Monte Cristo

The Second Part of the Reaction Paper on the Count of Monte Cristo Movie. The Count of Monte Cristo is a great story that helps you to realize how far the reaches of vengeance can really go. When the Count is going around ruining people it seems like he is more of a machine than a person. It seems like he has no emotions and can’t forgive the people who hurt him. Although some people might argue that the people who wronged the Count truly had what was coming to them, some of the Count’s actions could be seen as unnecessary. In the end everyone will be punished or rewarded by God and you shouldn’t be worried about what other people do or say as much as you are worried about yourself. “God will give me justice,” this line which was engraved in the wall on the prison was retained on my mind when I watched the movie” The Count of Monte Cristo.” This movie amazed me very much because of its excellent theme. I really like the story because it has a mixed of drama, suspense and rom

PROVEN and TESTED: Step-by-step guide to Register Alumni Association with SEC Philippines

Registering and Incorporating your High School or College Alumni Association with the Securities and Exchanges Commission (SEC) is a straightforward process now especially that SEC already have an online process. Here is how we registered our Non-stock and non-profit alumni organization with the SEC in less than a month process. Prepare the personal information of your incorporators Before going to the SEC website, you will the the following information of your incorporators prepared: Complete name such as their first name, middle name, last name Birth date Address, and  TIN number Use the SEC eSPARC Online Company Registration Go to the SEC website and look for the Online Services and select SEC eSPARC and click on the Regular Processing. Alumni associations are non stock corporation so you won't be able to avail of the OneSEC Processing. Remember the following important step: Select the nearest SEC office from your area, you will need to bring the signed and printed copy later o

Pluggle Review: 6 Reasons Why I doubt Pluggle and Why I'm Not Joining

First thing first, I am not concluding that this Pluggle is a scam because as per my observation and as far as my knowledge is concerned, people including my close friends seems profiting from this scheme and got the money they invested into it in a short period of time, and with profit ( although I'm sure the return of investment they got was paid by the people they invited and not from the company itself ). I think there's no doubt as to their legitimacy because, YES they are legitimate and are registered with the Securities and Exchange Commission of the Philippines as PLUGGLE INC. Are they scam? " Scam " is defined as a " dishonest scheme or a fraud ", are they being dishonest? I think no because they intend to do what they say. Are they " fraudulent "? Fraud is defined as " wrongful or criminal deception intended  to result in financial or personal gain "? This is also vague but I think I was struck by the last pa