Action Mailer(現場Railsより抜粋)

「タスクが保存できたらユーザーにメールを送信する」そんなメソッド、作ってみたいですよね。Railsにデフォルトで搭載されているActionMailerを使えば、その願望叶えられます。

一緒に実装していきましょう。

実装手順

$ bin/rails g mailer TaskMailer
app/mailers/task_mailer.rb

class TaskMailer< ApplicationMailer
  def creation_email(task)
    @task = task
	//メール本文のテンプレートを作成するためにインスタンスを作成している。
    mail(
      subject: 'タスク完了メール'
      to:'user@example.com'
			from: 'taskleaf@example.com'
			)
	end
end

email送信者のデフォルトを作成している

class ApplicationMailer < ActionMailer
  default from: 'taskleaf@example.com'
	layout 'mailer'
end

テキスト形式かHTML形式か検討する必要がある。

html形式

app/views/task_mailer/creation_email.html.slim

|以下のタスクを作成しました
ul
 li
   |名称: 
   = @task.name
 li
   |詳しい説明:
   = simple_format(@task.description) 

text形式:app/views/task_mailer/creation_email.text.slim

|以下のタスクを作成しました
= "\\n"
|名称: 
= @task.name
= "\\n"
|詳しい説明:
= "\\n"
= simple_format(@task.description) 

メール送信処理

app/controllers/tasks_controller.rb

def create
  @task = current_user.tasks.new(task_params)
  
  if params[:back].present?
    render :new
		return
	end

	if @task.save
	  TaskMailer.creation_email(@task).deliver_now -①
    redirect_to @task, notice: "タスク「#{@task.name)を登録しました。"

  else
    render :new
  end
end

①は即時送信用のメソッド

下記のようにすることで5分後に送信することもできる。

TaskMailer.creation_email(@task).deliver_later(wait: 5.minutes)

動作確認

mailcatcherをインストールする

$ gem install mailcatcher

taskleafのdevelopment環境でmailcatcherのSMTPサーバを利用するという設定をアプリケーション側に追加する必要がある。

config/environments/development.rb

# Don't care if the mailer can't send
config.action_mailer.raise_delivary_errors = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: '127.0.0.1', port: 1025 }

本番環境の場合はconfig/environments/production.rbに記載する。

mailcatcherを起動する

$ mailcatcher
Starting MailCatcher

起動後、task作成時に自動でメールが送信されるようになる。

ブラウザでhttp://127.0.0.1:1080にアクセスすると、メール管理画面にいくことができる。

Action Mailer の基礎 - Railsガイド