LoginSignup
2
2

More than 1 year has passed since last update.

[Rails]Action Mailboxとはメール受信時の処理を行うライブラリ

Posted at

はじめに

Rails6から追加された、メール受信時の処理を行う機能を提供するAction Mailboxというライブラリ。比較的新しい機能で使う機会がなかったのですが、機会が巡ってきたので、備忘録を書こうと思います!

対応するメールサービス、メールサーバ

  • Mailgun
  • Mandrill
  • Postmark
  • SendGrid
  • Exim
  • Postfix
  • Qmail

利用方法

※今回は本番環境でSendGridを利用することを想定して実装します。

1.ActiveJobので読み込むキューを設定する。

config/sidekiq.yml
:queues:
  ...
  - action_mailbox_routing
  - action_mailbox_incineration

2.ActiveStorageの保存先をクラウドストレージサービス(S3等)に変更する。

3.Action Mailboxのセットアップを行う。

$ rails action_mailbox:install

$ rails db:migrate

3.SendGridを利用する設定を追加する。

config/environments/production.rb
Rails.application.configure do
  ...
  config.action_mailbox.ingress = :sendgrid
end

4.rails credentials:editを実行して、外部からのリクエストを認証するパスワードを設定する。

...
action_mailbox:
  ingress_password: 任意のパスワード

5.受信メールを/rails/action_mailbox/sendgrid/inbound_emailsに転送するようSendGridのInboundParseを設定します。

<例>
https://actionmailbox:PASSWORD@任意のドメイン/rails/action_mailbox/sendgrid/inbound_emails

6.基本的なルーティングを設定する。

app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
  # 正規表現にマッチしたメールは、指定したActionMailboxに処理が振り分けられる
  routing /^save@/i     => :forwards

  # ブロック引数を受け取り判断処理
  routing ->(inbound_email) { inbound_email.mail/.to.size > 2 } => :multiple

  # すべてのメールにマッチする
  routing :all => :backstop
end

7.メールボックスを生成する。

$ rails g mailbox comments

8.メールボックスの設定を行う。

app/mailboxes/forwards_mailbox.rb
class CommentsMailbox < ApplicationMailbox
  # 処理に必要な条件をコールバックで指定する
  before_processing :validate_request

  def process
    board.comments.create!(body: mail.decoded, creator: commenter)
  end

  private

  def require_forward
    return if commenter && board

    # 引数で受け取ったActionMailerオブジェクトに対して、deliver_latorメソッドを実行してメール送信
        # InboundMailの状態をbouncedに変更する
    bounce_with CommentMailer.invalid_request(
      inbound_email, commenter: @commenter, board: @board
    )
  end

  def commenter
    return @commenter if defined?(@commenter)
    @commenter = User.find_by(email: mail.from)
  end

  def board
    return @board if defined?(@board)
    @board = Board.find_by(id: mail.to.split('-')[0])
  end
end

10.メールが削除される日数を設定する。(デフォルトでは30日間)

config/environments/production.rb
...
config.action_mailbox.incinerate_after: 100
...

受信したメールの状態

状態 意味
pending 初期状態
processing 処理中
delivered 処理が正常終了した
failed 処理中に例外が発生した
bounced 処理の実行を中止

開発を支援するWeb UI

実際にSendGridを用いなくても、動作確認を行うことができるWebUIを提供しています。
必要なデータを作成し、以下のURLにアクセスする。
この画面でメールを送信することで、詳細情報画面に遷移し、いろんな情報を確認できます。

終わりに

こういった機能を標準で装備されているのは嬉しい限りですね!Githubのようなプルリクにコメントが来た際にメールが来ますが、そのメールに返信するとコメントとして返信できるような機能も実装できるので、利用幅が広いなと思いました。

参考

Action Mailbox の基礎

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