Movatterモバイル変換


[0]ホーム

URL:


酒と泪とRubyとRailsと

Action Mailerの使い方


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
classMessage< ActionMailer::Base
# デフォルトでの送信元のアドレス
defaultfrom: from@example.com

defhello(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_helper

RSpec.describe Notifications,type::mailerdo
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
classMessage< ActionMailer::Base
add_template_helper(ApplicationHelper)
end

🎃補足: Action Mailerのコールバック

Action Mailerにはbefore_actionafter_actionおよびaround_actionというコールバック処理があります。

  • before_actionを使うことで、デフォルト値のセットやヘッダを挿入できます
  • after_action はMailerのアクション内のインスタンス変数を利用した設定を行うことができます
# app/mailers/user_mailer.rb
classUserMailer< ApplicationMailer
after_action:set_business_headers

defcampaign_message(business, user)
@business = business
@user = user
end

private

defset_business_headers
if @business
headers[X-SMTPAPI-CATEGORY] = @business.code
end
end
end

😼参考リンク

🖥 VULTRおすすめ

VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!

📚 おすすめの書籍

Rails/Modelバリデーションコールバック変更前後の値の確認値の保存・更新アソシエーション削除メソッドSQLの実行日付カラムの設定便利なDB関連設定読込み専用(Read Only)Concern(共通処理)クエリTipsRails/Controllerrenderレシピ集HTTPステータスシンボルIPの取得についてStrong ParametersControllerのTipsRails/ViewHAMLチートシート画像アップロードフォームS3への画像アップロードForm Objectフォームヘルパー検索可能なselectタグenum - selectタグシンプルな検索ボックス別ウィンドウ・フォームRailsいろいろi18nについてRails.cacheメール送信ロギングCapistrano3でデプロイセッション管理環境ごとのYAML設定読込xx分前の時間表記Tipsいろいろ便利ライブラリ簡単Webmock:VCRN+1対策:bullet環境変数の管理: dotenvi18nサポート: i18n-tasksLDAP:net-ldapヘッダ:secureheadersrack-mini-profileractiverecord-precountカバレッジ計測パンくずリスト+MetadataRSpecの記法自動修正アプリランキング取得Unicorn導入手順unicorn-worker-killerRSpecController SpecCapybaraとヘッドレスChromeRequest SpecAPI認証 Spec便利Tipsデザインパターン概要アブストラクトファクトリビルダファクトリメソッドアダプタコンポジットデコレータプロキシコマンドインタプリタイテレータオブザーバストラテジテンプレートメソッドRuby基礎文字列/String配列/Arrayハッシュ/Hash構造体/StructSpawn(コマンド実行)BundlerについてTipsRails 5.1へのアップデートRails 5へのアップデートrbenvバージョンアップpumaをsystemdで動かすURI.encodeとCGI.escapeURLのパラメータを変更処理時間を計測画像JPEG/PNG/GIF判定トラブルシュートNo route matches assets

[8]ページ先頭

©2009-2025 Movatter.jp