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.


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.


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 ( 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:

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

    def deliver!(mail)
      from = mail.from.first)
      to =
      subject = mail.subject
      content = 'text/plain', value: mail.body.raw_source)
      mail =, subject, to, content)

      sg = settings[:sendgrid_api_key])
      response = sg.client.mail._('send').post(request_body: mail.to_json)"SendGrid API called. Response code: #{response.status_code}")

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.

require 'send_grid_integration/my_delivery_method'
ActionMailer::Base.add_delivery_method :my_send_grid, SendGridIntegration::MyDeliveryMethod

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:

config.action_mailer.delivery_method = :my_send_grid
config.action_mailer.my_send_grid_settings = {
  sendgrid_api_key: ENV['SENDGRID_API_KEY']

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:

class ContactMailer < ApplicationMailer
  def thanks(contact)
         subject: 'Thanks for the Contact',
         content_type: 'text/plain',
         body: "#{}, thanks for taking the time to contact us!")

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:

def create
  @contact =

  respond_to do |format|

      format.html { redirect_to @contact, notice: 'Contact was successfully created.' }
      format.json { render :show, status: :created, location: @contact }
      format.html { render :new }
      format.json { render json: @contact.errors, status: :unprocessable_entity }

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

AWS Lambda+Python3で複数のRDSを起動停止

aws python rds



  • boto3でRDSを操作するために高レベルAPIのResourcesを使いたかったけど、RDSは提供されていないようなので低レベルAPIのClientsを使用
  • AWSアカウントの指定リージョン全てのRDS情報を取得
  • RDS情報より指定したタグとRDSのステータスによりフィルタリング(すでに停止されているRDSを停止しようとすると、スクリプトでエラーとなるため)
  • フィルタリングされたRDSを起動停止


  • python3.6
  • boto3


AWS DeepLensを購入しました〜セットアップ編〜




SIGNATEさんのData Science Competitionに出題しました

2018/3/20 ~ 2018/5/21の期間で、Data Science CompetitionでLINKBALのコンペを開催してもらいました。








Postmanは、Web APIのテストクライアントサービスのひとつです。色々なクライアントの動きをテストできるようスクリプト拡張や、テストスイートシナリオの作成などの機能があります。Postmanで、認証、テスト、ドキュメント作成、バージョン管理などAPIの多くの要素を統合して開発できる環境で、API設計・開発にはとても助かります。



リンクバル技術部の川畑です。先日弊社でリリースしました、リアルタイム飲み会マッチングアプリ together の裏側のアーキテクチャについて、ANKEY主催のセミナー クラウドヂカラ #AWSセミナー 〜エンジニアに求められる本当のスキルとは〜 のLT枠で発表させて頂きましたので、その内容を紹介させて頂きます。