&tag(Rails3/メール送信); *目次 [#k1df0f71] #contents *参考情報 [#z27a9a25] -[[Action Mailer Basics ― Ruby on Rails Guides:http://edgeguides.rubyonrails.org/action_mailer_basics.html]] … 公式サイトが一番くわしいのでめんどくさがらず読んだほうが良い。 -[[RailsのActionMailerを使いGmail経由でメール送信する - ばくのエンジニア日誌:http://bakunyo.hatenablog.com/entry/2013/04/24/Rails%E3%81%AEActionMailer%E3%82%92%E4%BD%BF%E3%81%84Gmail%E7%B5%8C%E7%94%B1%E3%81%A7%E3%83%A1%E3%83%BC%E3%83%AB%E9%80%81%E4%BF%A1%E3%81%99%E3%82%8B]] -[[Rails3]] *基本 [#yf652d63] **概要 [#qcda7f6f] -デフォルトでActionMailerという仕組みが組み込まれていて簡単にメールを送信することができる。 -Gemに追加するとか必要なし。 **設定ファイル変更 [#w73d6f40] -smtpサーバーに関する設定を、development.rb / production.rbなどで行う。 -開発環境では通常postfixなどローカルのsmtpサーバーが動いていないので、smtp_settingsでいろいろ設定してやらないといけない。以下どこかよそのsmtpサーバーを使って認証してから送信するdevelopment.rbの例。 #pre{{ config.action_mailer.raise_delivery_errors = true config.action_mailer.default_url_options = { :host => "localhost", :port => 3000 } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "my.smtp.com, :port => 587, :user_name => "[email protected]", :password => "smptpass", :authentication => 'plain', :enable_starttls_auto => false, } }} -本番環境で、smptサーバーがローカルで動いている場合、簡単な設定ですむ。以下単純にlocalのsmtpサーバーを使うだけの。production.rbの例 #pre{{ config.action_mailer.raise_delivery_errors = true config.action_mailer.default_url_options = { :host => "localhost", :port => 3000 } config.action_mailer.delivery_method = :smtp }} **ファイル生成 [#na27235e] -railsコマンドでひな形を生成できる。app/mailers/user_mailer.rbとapp/views/user_mailerという空ディレクトリが作成される。 #pre{{ $ bundle exec rails generate mailer UserMailer create app/mailers/user_mailer.rb invoke erb create app/views/user_mailer invoke test_unit create test/functional/user_mailer_test.rb }} ***user_mailer.rbの作成 [#o7852f90] -app/mailers/user_mailer.rbを編集する。 -controller的な役目で、インスタンス変数に設定するとビュー側から参照できるのも同じ。 #pre{{ class UserMailer < ActionMailer::Base default from: "[email protected]" def hello @greeting = "Hi" mail to: "[email protected]" end end }} ***hello.text.erbの作成 [#f6a8e5a1] -app/views/user_mailer/hello.text.erbを作成する。 -view的な役目。hello.text.erbの場合テキスト形式のメールとなる。 #pre{{ テストメッセージです。 <%= @greeting %> }} **送信 [#zb9880f2] -どこかのコントローラーのアクションから以下のように呼び出す UserMailer.hello. deliver