LoginSignup
33
31

More than 5 years have passed since last update.

VPSからRailsのActionMailerでメールを送信する(≠gmail経由)

Last updated at Posted at 2014-01-25

PHPでPostfixを利用して、簡単にメールを送る方法は調べれば出てきます。
PHPで作るお問い合わせメールフォーム(自動返信機能付き)

同じようなことをRailsでやりたくて、ネットを調べたのですがGmail経由の情報は合ったのですが、独自ドメインで送信する方法が見つからなかったので、ご紹介します。
RailsのActionMailerでメールを送信する(Gmail経由)

Postfixがインストールされているかの確認

VPSなどからメールを送る際には、SMTP(Simple Mail Transfer Protocol)に則ったソフトウェアが必要になります。色々種類は有りますが、ここではPHPのメール送信で利用したPostfixを利用します。

PostfixはVPS上で以下のコマンドで入っているかどうか確認することができます。(yumでインストールされた中で、postfixを検索検索!)

Terminal
$ yum list installed | grep postfix
postfix.x86_64       2:2.6.6-2.2.el6_1  @anaconda-CentOS-201303020151.x86_64/6.4

postfix…と表示されれば、インストールされています!もし表示されなければyumでインストールして下さい

Terminal
$ sudo yum install postfix

メールを送るための環境設定

メールを送るための環境設定を行います。とりあえずは開発環境のみで使う設定を行います。
Postfixはデフォルトでローカルから特に認証をせずにメールを送ることができるので、saslauthdなどの認証は不要。
また、config.action_mailer.raise_delivery_errors=trueを設定しないとメールが送れていなくてもエラーメッセージが表示されません。デフォルトでfalseになっているので、trueに変えましょう。

/config/environments/development.rb
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address => 'localhost'
}

メールを送るクラスの作製

メールを送るためのコントローラ、送信するメールの内容を記述するクラスを自動生成します

Terminal
# rails g mailer クラス名 メソッド名

$ rails g mailer NoticeMail sendMail

メールクラスの編集

メールを送るアドレスや、送信先などを設定します。

/app/mailers/notice_mail.rb
class NoticeMail < ActionMailer::Base
  #送信元のアドレス
  default from: "from@example.com"

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.notice_mail.sendMail.subject
  #
  def sendMail
    @greeting = "Hi"

    #宛先メールアドレス
    mail to: "to@example.org"

    #送信メールの件名
    mail subject: "テストメールです" 
  end
end

メール内容の編集

生成されたテンプレートの拡張子を~.html.erbにすればHTMLメール、~.text.erbにすればテキストのメールを送ることができます

/app/views/notice_mail/sendMail.text.erb
NoticeMail#sendMail

<%= @greeting %>, find me in app/views/app/views/notice_mail/sendMail.text.erb

テストメールです!!

これで、メールを送ることができます!Railsのコンソールで確認してみましょう。

Terminal
$ rails c
NoticeMail.sendMail.deliver

Viewからメールの送信

Viewの中からメールを送信するには、バタンなど押されたときにアクションとして書いてあげればOKです!
まずはコントローラにリンクが押された時のアクションを作り、ルートを定義します。

Terminal
#コントローラとビューの作成
$ rails g controller MailList top
/app/controllers/mail_list_controller.rb
  #メールを送るアクション
  def go_mail
    NoticeMail.sendMail.deliver
    render :text => '送信完了!'
  end
/config/routes.rb
  #メールを送るアクションのルート定義
  get 'go_mail' => 'mail_list#go_mail'

あとはViewに押されたときにアクションを実行するリンクを作ります。

/app/views/mail_list_top.html.erb
<%= link_to "メール送信", :action => 'go_mail' %>


エラーが起きずに送信されればバッチグーです!!
お疲れ様でした^^

33
31
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
33
31