Railsにはメールを送信してくれるAction Mailerという機能が標準で組み込まれています。 この機能を使えばアプリケーションからメールを簡単に送信できます。
🐠 環境設定 Development環境で、メール送信に関するエラーをログに出力するようにします。
# config/environments/development.rb config.action_mailer.raise_delivery_errors =true
TestApp::Application.configure内にメール送信用の設定をしてください。
# config/environments/development.rb # ↓ 以下を追加 config.action_mailer.default_url_options = {host: localhost,port: 3000 } config.action_mailer.delivery_method =:smtp config.action_mailer.smtp_settings = { address: SMTPのメールサーバ,port: 587 ,domain: '送付するドメイン' ,user_name: メールサーバ認証用ユーザー,password: メールサーバ認証用パスワード}
🗻 Mailerファイルの生成 次のコマンドでMailerに関するファイルをまとめて生成できます。
rails g mailer message hello create app/mailers/message.rb create app/mailers/application_mailer.rb invoke haml create app/views/message create app/views/message/hello.text.haml invoke rspec create spec/mailers/message_spec.rb create spec/fixtures/message/hello create spec/mailers/previews/message_preview.rb
🐮 Mailerクラスの編集 次にMailerでメールを送信してみます。まずはメインのメソッドを作成します。
# app/mailers/message.rb class Message < ActionMailer::Base# デフォルトでの送信元のアドレス defaultfrom: from@example.com def hello (name) @name = name mail( # TOは単体のメールアドレスでもArrayのメールアドレスでも大丈夫 to: 'to@example.net' ,subject: 'Mail from Message' , )do |format| format.html end end end
メール用のViewを編集します。html形式だけでなく、text形式も利用可能です。
-# app/views/message/hello.html.haml = There is#{@name }'s body.
コマンドラインからメールを送信してみます。
# Rails console に入る rails c # メール送信 Message.hello.deliver
これでメールが、Messageクラスの『to@example.org 』に送信されていれば、メール送信成功です。
🏀 MailerのRSpec 以下は、Action MailerのRSpecのサンプルです。
require rails_helperRSpec.describe Notifications,type: :mailer do describe#signup do let(:mail ) { described_class.signup } it renders the headersdo expect(mail.subject).to eq(Signup) expect(mail.to).to eq([to@example.org]) expect(mail.from).to eq([from@example.com]) end it renders the bodydo expect(mail.body.encoded).to match(Hi) end end end
type: :mailerを指定することでRSpec-railsのmailer用のメソッドを使うことができます。
😎 補足:Action MailerのView内でHelperメソッドを使う場合 Action MailerのView内でhelperメソッドを使いたい場合は、add_template_helper(ApplicationHelper)を追加すればつかえるようになるそうです。
# app/mailers/message.rb class Message < ActionMailer::Base add_template_helper(ApplicationHelper) end
🎃 補足: Action Mailerのコールバック Action Mailerにはbefore_action、after_actionおよびaround_actionというコールバック処理があります。
before_actionを使うことで、デフォルト値のセットやヘッダを挿入できますafter_action はMailerのアクション内のインスタンス変数を利用した設定を行うことができます# app/mailers/user_mailer.rb class UserMailer < ApplicationMailer after_action:set_business_headers def campaign_message (business, user) @business = business @user = user end private def set_business_headers if @business headers[X-SMTPAPI-CATEGORY] = @business.code end end end
😼 参考リンク
🖥 VULTRおすすめ 「VULTR 」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTR のヘビーユーザーになので、「ここ 」から会員登録してもらえるとサービス開発が捗ります!