Ever wanted to merge Gmail seamlessly into your Rails app but couldn't find much help? Don't worry, I've got your back! In this tutorial, I'll walk you through the basic steps to integrate Gmail into your Rails project. By the end, you'll be all set to supercharge your app with Gmail's features for smoother communication and automation.

1. Set Up a Google App with Gmail API Access

Head over to https://console.cloud.google.com/ and create a new project. Once you've got that set up, navigate to the APIs & Services section. Hit the button to enable APIs and search for the Gmail API. Once you've found it, just click to enable it, and it will be added to your project.

2. Configure the consent OAuth page

Once you have added the Gmail integration to your project, navigate to the "OAuth consent screen" and configure it for your application.

The app will request certain information to display when the user logs in. Include the Gmail scope for this purpose. You can view all possible scopes here.

After configuration, add your email (or another one) as a test user. This allows you to log into your app without issues while it's not yet in production:

3. Create the credentials for your app

Navigate to the "Credentials" tab as shown in the image above. Click on the option to create a new credential and choose "OAuth client ID.”

Opt for "Web application" as the application type. Specify the authorized origin by providing the server domain along with the protocol (you can also use http://localhost:3000 for local testing).

Next, set up the authorized redirect URIs. This URI should be a GET endpoint within your app where Google can redirect the user after they've completed the OAuth consent process. Google will append a code parameter to this endpoint.

Once you've configured these settings, create the client ID. Make sure to copy both the client ID and the client secret for later use.

4. Add the Ruby Client for Google API in your Gemfile

Add the following to your Gemfile:

gem "google-apis-core" # For authenticating in Google integration
gem "google-apis-gmail_v1" # For in-app email sending
gem "rmail" # For formatting the email

This gem is automatically generated from Google docs, resulting in somewhat limited documentation for the gem itself. You might also find it useful to use the rmail gem for generating email messages. It seems to be compatible with other email providers as well!

5. Set Up endpoint for redirecting users to consent screen

Now, let's create a GET endpoint in your app that redirects users to the following URL:

"https://accounts.google.com/o/oauth2/auth" \
  "?client_id=#{client_id}" \
  "&redirect_uri=#{redirect_uri}" \
  "&response_type=code" \
  "&scope=https://www.googleapis.com/auth/gmail.send" \
  "&access_type=offline" \
  "&prompt=consent&"
  • Client ID: Obtain this from step 3.
  • Redirect URI: Should match the one set during credential creation in step 3.
  • Scope: Ensure it matches the required scopes configured during step 2. If you have multiple scopes, separate them with %20, like this: &scope=https://www.googleapis.com/auth/gmail.send%20https://www.googleapis.com/auth/userinfo.email.
  • Access Type: Set as offline and prompt as consent to ensure the refresh token is always obtained, even if the user has disabled and then re-enabled the configuration.

After implementing this step, users should be able to visit this endpoint, get redirected to the OAuth consent page, log in with a test email (as set in step 2), and then be redirected back to the specified redirect URI. This ensures a seamless flow for users to grant necessary permissions to your app.

6. Configure the redirect URI for google

Now, specify the endpoint to which Google will redirect the user. Google will call this endpoint with a code parameter. You can subsequently use this code to exchange it for an access token or refresh token. First, include the necessary gems in your config/application.rb file:

require "google/apis/oauth2_v2"
require "google/apis/gmail_v1"
require "google/api_client/client_secrets"

Next, navigate to the controller or service invoked by the redirect endpoint and create the authorization object:

auth_client = Google::APIClient::ClientSecrets.new({
  web: {
    client_id: client_id,
    auth_uri: "https://accounts.google.com/o/oauth2/auth",
    token_uri: "https://oauth2.googleapis.com/token",
    client_secret: client_secret,
    redirect_uris: [redirect_uri],
  },
}).to_authorization

You can obtain the client_secret from step 3.

Next, exchange the code for an access token:

auth_client.code = params[:code]
auth_client.fetch_access_token!

You can observe that the auth_client is now populated with the access_token parameter.

Build the message using Rmail:

message = RMail::Message.new
message.header['To'] = "example@superfiliate.com"
message.header['From'] = "employee@superfiliate.com" # here it needs to be the integrated email
message.header['Subject'] = "Hello"
message.header['content-type'] = ' text/html; charset=ISO-8859-1'
message.body = "<b>bold</b> Hello!"

And now let’s send it!

gmail = Google::Apis::GmailV1::GmailService.new
gmail.send_user_message('me',
                        upload_source: StringIO.new(message.to_s),
                        content_type: 'message/rfc5322',
                        options: { authorization: auth_client })

Now, check your inbox. You should see the email there.

Observations

While this tutorial provides a straightforward approach to integrating Gmail into your Rails application, real-world applications often require additional considerations.

For a production-grade application:

  1. Token Management: Consider implementing a more robust token management system. Upon receiving the code from the redirect endpoint, exchange it for a refresh token and securely store it in your database.
  2. Email Sending Endpoint: Create another endpoint dedicated to sending emails using the refresh token retrieved earlier. This separation of concerns helps maintain a clean and organized codebase.

By implementing these additional features, you ensure a more secure and scalable solution for integrating Gmail functionality into your Rails application.

References