Adding a Rails Email Delivery Method to Work with SendGrid’s Web API

Hi! I’m Dennis and I’ve been working at Linkbal as a software engineer since October 2017.

In this article, we are going to create a new ActionMailer delivery method that works with SendGrid through its Web API and integrate it to a simple Rails project created with scaffolding. This post assumes you are already have some familiarity with Ruby on Rails.

目次

Introduction

When searching for information about how to integrate Rails projects to SendGrid, we are usually presented with articles that describe how to do it through SMTP. That is the case even in SendGrid’s own Knowledge Center. This is the easiest implementation for sure as it requires very little setup.

But, what if we want to use SendGrid’s Web API instead? Well, there’s no official plug&play option as is the case for other services, such as Postmark. There are unofficial options, such as this gem, but they are not much popular and sometimes we just want a simpler email delivery implementation. In this case, we can create our own implementation to customize ActionMailer to use SendGrid’s Web API.

Preparation

Test Rails Project

Let’s create a minimal Rails project to test our implementation:

$ rails new sendgrid_integration_test
$ cd sendgrid_integration_test

Now, we are going to a very simple contact form through scaffolding:

$ rails generate scaffold Contact name:string email:string message:text
$ rails db:migrate

SendGrid API Key

To use SendGrid’s API, we need to create a new SendGrid account if we don’t have one (there’s a free trial period and, after that, we can send up to 100 emails a day for testing purposes) and create a new API key (it’s good practice to remove API keys when they are not needed anymore). It will be used for authentication and authorization when using the API. In the SendGrid dashboard, go to Settings > API Keys and click the “Create API Key” button.

Setting to manage API keys

Give it any name you want and choose the “Restricted Access” option, so we can customize the access level for the key. For this guide, it should be enough to set “Mail Send” to “Full Access”, as shown below.

Creating a SendGrid API key and customizing its permissions

Confirm and the key will be displayed to you. It is just displayed once for security reasons and the page recommends us to save it somewhere safe.

Environment Variable for the Key

We are now going to set the newly created API key as an environment variable:

$ export SENDGRID_API_KEY='api_key_copied_from_sendgrid_dashboard'

To make this permanent, add the line above to .bash_profile if you are on a Mac or to .bashrc if on Linux.

sendgrid-ruby gem

Before we start creating our new delivery method, let’s add the official Ruby API library (https://github.com/sendgrid/sendgrid-ruby). We are going to use it to communicate with SendGrid’s Web API. Just add the line below to the project’s Gemfile:

gem 'sendgrid-ruby'

And update the dependencies:

$ bundle install

New Delivery Method

The implementation of our new delivery method will be in the lib/send_grid_integration/my_delivery_method.rb file, which contents are shown below:

[ruby] require ‘sendgrid-ruby’

module SendGridIntegration
class MyDeliveryMethod
attr_accessor :settings

# settings is a hash to be added to the configuration of the environment that will use MyDeliveryMethod
def initialize(settings)
self.settings = settings
end

def deliver!(mail)
from = SendGrid::Email.new(email: mail.from.first)
to = SendGrid::Email.new(email: mail.to.first)
subject = mail.subject
content = SendGrid::Content.new(type: ‘text/plain’, value: mail.body.raw_source)
mail = SendGrid::Mail.new(from, subject, to, content)

sg = SendGrid::API.new(api_key: settings[:sendgrid_api_key])
response = sg.client.mail._(‘send’).post(request_body: mail.to_json)

Rails.logger.info("SendGrid API called. Response code: #{response.status_code}")
end
end
end
[/ruby]

This was kept as simple as possible as this is not an article on how to use the official Ruby API library. It only supports text emails and does not support cc, bcc or attachments. You can take a look at the sendgrid-ruby repository for details on how to implement the missing features, especially this example file.

Initializing the New Delivery Method

We need to run some intialization code to make our new delivery method available to our application. To do so, add the code below to config/application.rb file.

[ruby] require ‘send_grid_integration/my_delivery_method’
ActionMailer::Base.add_delivery_method :my_send_grid, SendGridIntegration::MyDeliveryMethod
[/ruby]

Environment Configuration

Now, we are going to configure our environment to use the new delivery method. Let’s also add a settings hash to illustrate how to pass parameters to our delivery method class. In our case, let’s configure the local environment file config/environments/development.rb by adding the lines below:

[ruby] config.action_mailer.delivery_method = :my_send_grid
config.action_mailer.my_send_grid_settings = {
sendgrid_api_key: ENV[‘SENDGRID_API_KEY’] }
[/ruby]

Time to Test

At last, we are going to add a new mailer to test our delivery method. Add the app/mailers/contact_mailer.rb file with the following content:

[ruby] class ContactMailer < ApplicationMailer
def thanks(contact)
mail(to: contact.email,
subject: ‘Thanks for the Contact’,
content_type: ‘text/plain’,
body: "#{contact.name}, thanks for taking the time to contact us!")
end
end
[/ruby]

Using the Mailer

At last, we are going to open the app/controllers/contacts_controller.rb file to use our mailer when a new contact happens. Edit the file to add a new line as shown below:

[ruby] def create
@contact = Contact.new(contact_params)

respond_to do |format|
if @contact.save
ContactMailer.thanks(@contact).deliver_now

format.html { redirect_to @contact, notice: ‘Contact was successfully created.’ }
format.json { render :show, status: :created, location: @contact }
else
format.html { render :new }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
[/ruby]

Run the Application

Let’s run our application:

$ rails server

And access http://localhost:3000/contacts to create a new contact. Fill the form and make sure to provide a valid email address you can access. You should receive a thanks email if the contact is saved without errors. You can monitor the emails sent by your SendGrid account by accessing the “Activity” menu in the service dashboard.

Activity menu in SendGrid dashboard