エンジニアリング

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:

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

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)
    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

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 = 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

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 DeepLensを購入しました〜セットアップ編〜


リンクバルでエンジニアをしております磯谷です。

何か新たなことをするべく、先日AWSDeepLensを購入しました。DeepLensに関する日本語の記事はまだまだ少ないということもあり、今回から数回に分けてDeepLensについての記事を書こうと思っております。

手始めに今回はセットアップ編です。
続きを読む


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


LINKBALでエンジニアをやっています磯谷です。
2018/3/20 ~ 2018/5/21の期間で、Data Science CompetitionでLINKBALのコンペを開催してもらいました。

そして7/5(木)に受賞者の方をお呼びして表彰式を行いました!

今日はそのコンペと表彰式について書かせていただきます。
↑の画像は表彰式で撮った集合写真です。

続きを読む


Postmanツールの機能紹介


エンジニアのクオンです。

今回は、業務でよくお世話になっているPostmanについて紹介させて頂きます。

Postmanとは

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

続きを読む


Chrome拡張おすすめ記事から選ぶおすすめ拡張20選

Chromeの拡張

はじめに

どうも、最近まったくの未経験からiOS担当になって日々ヒーヒー言っているキンチキこと水野です。

ネットの海にある数多のChrome拡張おすすめ記事で紹介されている拡張から、実際に僕が使っておすすめの拡張を紹介します。あとはおすすめ記事でおすすめされてないけど、僕がおすすめするものも紹介します。

拡張を全然使っていない人が意外とエンジニアにもいて、もっと楽すればいいのにと思ってます。そして、エンジニアよりPC操作にあまり慣れていない人にこそ拡張はおすすめなので、便利なものはガンガン入れましょう!

続きを読む


Alexa!スキル開発のやり方を教えて!①


4月に新卒入社しました、村上です。

私は入社前にアルバイトとして業務に携わっていたのですが、
そのアルバイト時代に「Alexaスキル」の開発を行いました。

そこで今回はその開発について振り返り、
・Alexaってそもそも何?
・Alexaスキルって何?
・どうやって開発するの?
ということを、初心者向けにご紹介したいと思います!

Alexaとは?

→Amazonが提供する「音声認識サービス」のことです。

続きを読む


Attending to the SendGrid’s Email Delivery Hands-On – Part 1


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

Today, I’d like to share how was my experience taking part in SendGrid’s mail delivery hands-on. I will mainly write about some background information and concepts that were presented and also about the first part of the hands-on, that included the initial setup, a simple email delivery test and the use of SendGrid’s dashboard to check the results.

Introduction

SendGrid is an US based company represented by KOZO KEIKAKU ENGINEERING Inc. here in Japan.

As you may already know, it provides one of the most well-known cloud-based transactional email delivery services, but also includes an email marketing platform. This article will focus on transactional emails as it was also the focus of the hands-on.

続きを読む