LoginSignup
6
7

More than 5 years have passed since last update.

ActionMailerでメール機能の実装

Posted at

お問い合わせなどがあったときにそのユーザーにメールが届くために

rails ではActionMailerという機能を提供しているので、これを利用してメール機能を実装します。まずコマンドで

command
$ rails g mailer InquiryNotifier

と打ちます。ファイルが自動生成されますが一旦ここでは気にしません。

mailerがメールを送るためにすることの流れは

0,sendgridでアカウントを作る
1,ActionMailerクラスを継承したInquiryNotifierクラスで送信する際のメソッドを定義
2,formでもらったデータを`InquiryController.rb`のcreateアクションにsendgridなどのメールクライアントをかませる
3,smtpの設定
4,メールの書く内容のにformのデータを反映

といったところです。

0,sendgridアカウントを作る

こちらから

1,ActionMailerクラスを継承したInquiryNotifierクラスで送信する際のメソッドを定義

inquiry_notifier.rb
class InquiryNotifier < ApplicationMailer

  def send_user(inquiry)
    @inquiry = inquiry
    mail(to: @inquiry.email, subject: 'お問い合わせありがとうございます。' )
  end
#@inquryはユーザがデータを投入するための変数です
end

2,formでもらったデータをInquiryController.rbのcreateアクションにsendgridなどのメールクライアントをかませる

inquries_controller.rb
....
  def create
    @inquiry = Inquiry.new(inquiry_params)#ストロングパラメータです
    if @inquiry.save
      InquiryNotifier.send_user(@inquiry).deliver_now #rails5ではdeliver_nowしか使えないのでこちらを推奨します。
      redirect_to root_path
    else
      render template: "welcome/index"
    end
  end
...

smtpの設定

config/production.rb

....
config.action_mailer.default_url_options = { :host => 'ホスト名' }
  config.action_mailer.smtp_settings = {
    :user_name => 'sendgridのユーザー名',
    :password => 'sendgridのパスワード',
    :domain => 'ドメイン名',
    :address => 'smtp.sendgrid.net',
    :port => 587,
    :authentication => :plain,
    :enable_starttls_auto => true
  }
...

を追加。

4,メールの書く内容にformのデータを反映

先ほどのコマンドで'layouts/miler.html'が自動生成されてるので、そこに埋め込むものが以下です。

send_user.html.erb
<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <p>ユーザ名 => <%= @inquiry.name %></p>
    <p>eメールアドレス => <%= @inquiry.email%></p>
  </body>
</html>

ローカルでもオンラインであれば実行できます(^o^)/
コードを追加してadminにも送ることもできるようになりますv(^_^v)♪

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7