Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | ActionMailerでRailsからメールを送信する

概要

ActionMailerでRailsからメールを送信する

内容

Railsでメール送信を行うにはActionMailerを利用します。

サンプル

development.rb(test.rb,production.rb)
config.action_mailer.raise_delivery_errors = true

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address => "smtp_server_name",
  :port => 25,
  :domain => 'domain',
}
Mailerの生成
rails g mailer ExtendedActionMailer hello
メール本文

下記のファイルにerb形式で記述します。
app/views/extended_action_mailer/hello.text.erb
app/views/extended_action_mailer/hello.html.erb

xxx.text.erbはテキスト形式
xxx.html.erbはHTML形式

環境ごとのメール送信有無を設定

Action::Mailerを利用していれば下記設定で送信の切り替えが可能
本番環境はメール有効
開発・テスト環境はメール無効

development.rb

config.action_mailer.delivery_method = :test

test.rb

config.action_mailer.delivery_method = :test

production.rb

# config.action_mailer.delivery_method = :smtp