Washington DC Google Hackathon - Apps Scripts

I recently had the pleasure of visiting Google Washington DC to attend a hackthon for apps scripts. Apps script allows to have several different Google products speak to each other. The results are pretty powerful but may be difficult to truly understand without an example.

Let's say you have an event that you want people to register to. You can use Google Docs to create a spreadsheet, that will create a form for users to fill out. When the form is filled out the spreadsheet will be populated with their data. The magic doesn't stop there, now you can use Gmail's apps script API to have it fire off an email to yourself and the register. Pretty cool consider this is the only way you can use an API to communicate with Gmail. In my hackathon script I created a spreadsheet that a mini Gmail client.
Here's a link to to hang out so you can check it out:



Here's the code I used:

function myFunction() {
  
  // Tells Apps script we want to edit the current spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  // Select the first sheet in the document
  var sheet = ss.getSheets()[0];
  
  // Get the data from your inbox
  // Here you can see we only get the first 15 emails
  var threads = GmailApp.getInboxThreads(0,15);
  
  // Selects C3 of our current sheet
  cell = sheet.getRange("C3");
  var cellValue = "";
  
  // Now we are going to loop over every item in our thread list
  for (var i = 0; i < threads.length; i++) {
    
    // Reset cell background colors to white
    // We do this because later we'll highlight starred emails
    cell.offset(0,0).setBackgroundColor("White")
      
    // Number next to email - add one because array starts at zero
    cell.offset(i,-1).setValue(parseInt(i)+1);
    
    // Get subject from email 
    var cellValue = threads[i].getFirstMessageSubject();
    cell.offset(i,1).setValue(cellValue+1);
    
    // Retrieves first message from thread and saves to cell 
    tMessage = threads[i].getMessages();
    var emailFrom = tMessage[0].getFrom();
    cell.offset(i,0).setValue(emailFrom);
    
    // If thread contains a star then make yellow
    if(threads[i].hasStarredMessages()) {
      cell.offset(i,0).setBackgroundColor("Yellow");

    }
    
  }
  
  sheet.getRange("C1").setValue("Unread Emails: " + GmailApp.getInboxUnreadCount());
}

Thanks everyone for watching. I'll be sure to add more tutorials on Apps Script in the future. Especially how to create a contact form using Apps Script and Gmail.

Popular posts from this blog

Connect to Gmail with Apps Script

How to create a Chrome Extension

Apps Script on tablets