LoginSignup
2
1

More than 3 years have passed since last update.

【Rails】ActionMailbox + Sendgrid + AWS(Route53) を実装してみた

Last updated at Posted at 2021-01-03

課題

Action Mailbox を実装してみたら意外と苦戦したので、未来の自分の為に纏め。
最低限の実装で取り敢えず動くところが目標です。

前提

  1. 既に記録対象となるRailsサーバはAWS(EC2)で動作
  2. DNSはAWS(Route53)を使用
  3. メール配信サービスはSendgridを使用

やること

  1. ActionMailbox を導入して受け取ったPOSTをRailsでよろしく処理する準備
  2. メールをSendgridに送る為、Sendgrid宛のmxレコードをRoute53に作成
  3. Sendgridから受け取ったメールをRailsの特定URLにPOSTする設定を投入

ActionMailboxの導入

Rails6では初期状態から以下コマンドでActionMailboxをインストールできます。

ActionMailboxをインストール
$ rails action_mailbox:install

ActiveStorageとActionMailboxのMigration Fileが作成されるのでmigrateして置きます。
この二つのテーブルの役割の説明は割愛します。

migrate
$ rails db:migrate

以下作成されたばかりの app/mailboxes/application_mailbox.rb です。
ここに受け取ったメールの処理を加えて行きます。

app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
  # routing /something/i => :somewhere
end

細かい事は沢山できますが、まずは単純に受けとった全てのメールに対して処理する内容とします。

app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
  routing all: :replies
end

class RepliesMailbox < ApplicationMailbox
  def process
    #Do something!!
  end
end

この時点で、以下URLにアクセスするとローカルで挙動が確認できます。
http://localhost:3000/rails/conductor/action_mailbox/inbound_emails/new
スクリーンショット 2021-01-03 11.39.04.png

外部からメールを受け取るようのパスワードを設定します。

credentialの設定
$ EDITOR="vi" bin/rails credentials:edit -e production
credential
action_mailbox:
  ingress_password: 'greatpassword'

最後に何処のメール配信サービスからリクエストが来るのか(今回はsendgrid)設定して完了です。

config/environments/production.rb
class ApplicationMailbox < ActionMailbox::Base
  ##省略##
  config.action_mailbox.ingress = :sendgrid
end

Sendgridの登録と設定

  1. こちらからSendgridに登録します。
  2. settings -> Sender Authentication -> Domain Authenticationと選択します。
  3. CNAMEを3つ入力しろと言われるのでRoute53に記載して確認します。 スクリーンショット 2021-01-03 11.57.30.png

----------ここから先はRoute53の設定が完了していることが前提です-----------

  1. settings -> Inbound Parse -> Add Host & URL と選択します。
  2. MXレコードとして記載したホスト名とURLを入力します。また、'POST the raw, full MIME message'のチェックも入れてください

[URL Example]
https://actionmailbox:greatpassword@host.example.com/rails/action_mailbox/sendgrid/inbound_emails

Route53の設定

  1. MXレコードを設定します。Name: 'なんでもいい', Target: 'mx.sendgrid.net', Priority: '10' スクリーンショット 2021-01-03 12.14.14.png
  2. Sendgridで指定されたCNAMEの登録

以上で取り急ぎ動作すると思います。

参考情報

Action Mailbox Basics
https://guides.rubyonrails.org/action_mailbox_basics.html

Rails 6のAction Mailboxを使ってみよう(翻訳)
https://techracho.bpsinc.jp/hachi8833/2020_03_05/88539

Rails6で導入されるAction Mailboxを試してみた
https://bagelee.com/programming/ruby-on-rails/rails6-action-mailbox/

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1