I turned off Gmail alerts on my phone a while ago. It just doesn’t make sense for my phone to beep every time someone comments on someone else’s status. That said, not all emails are created equal. There are some messages for which I would like to know right now when they show up in my inbox. SMS alerts are great for customized, urgent notifications like this.

This is a two part tutorial on how to build SMS email alerts in Ruby on Rails using the GMail API and Twilio. Part One is on how to authenticate your Rails app with a Google API using OAuth — and though our app uses Gmail, the OAuth process is the same for all Google APIs, so all this will work for the Calendar API, the Drive API, etc. with only minor adjustments. Part Two will teach you how to retrieve emails from the Gmail API in Rails and how to send SMS alerts using Twilio.

Google APIs and OAuth

The goal of this series is to write a script that checks our e-mail. To do that, we’ll first need to authenticate with Google via OAuth to access our account data. Even if you’ve never written an OAuth authorization before, you’ve undoubtedly used it. OAuth is what’s happening in the background when you encounter this screen:

From the developer’s perspective, the OAuth process looks like this:

You set up an app within Google’s developer portal and tell it what APIs you’d like to use and Google gives you a Client ID and Client Secret (basically, a username and password). When a user signs into your app, your app redirects them to Google and passes along the client id/secret. Google asks the user permission to access their GMail data Google calls back to your app and sends a code which you can use, along with your credentials, to retrieve an access token with which you can make authenticated API calls.

Now you could write this OAuth process flow by hand, but why reinvent that rather complicated wheel? Omniauth is the de facto standard way to perform OAuth authentication in the Ruby world. Fortunately, there’s an add-on gem (“swappable strategy” in Omniauth speak) written specifically for the the Google API. In the rest of this post, we’ll talk about how to:

Create a Rails app with the the gems needed to connect to a Google API

Configure Omniauth to perform the Oauth dance with Google

Set up your app on the Google developer portal

Save and refresh your Google API access token

Sound good? Then let’s get started…

Create a Rails project for Omniauth and the Gmail API

Open a terminal, navigate into your code directory and type: