199
202

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsのActionMailerでメールを送信する(Gmail経由)

Posted at

##環境設定
config/environments/development.rbを以下のように設定

/config/environments/develop.rb

config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = true
config.action_mailer.smtp_settings = {
  :enable_starttls_auto => true,
  :address => 'smtp.gmail.com',
  :port => '587',
  :domain => 'smtp.gmail.com',
  :authentication => 'plain',
  :user_name => 'ユーザー名@gmail.com',
  :password => 'gmailパスワード'
}

##メーラークラスを自動生成

#rails generate mailer クラス名 メソッド名

$ rails generate mailer NoticeMailer sendmail_confirm
      create  app/mailers/notice_mailer.rb
      invoke  erb
      create    app/views/notice_mailer
      create    app/views/notice_mailer/sendmail_confirm.text.erb
      invoke  test_unit
      create    test/functional/notice_mailer_test.rb

##メーラークラスの編集

/app/mailers/notice_mailer

class NoticeMailer < ActionMailer::Base
  #デフォルトのヘッダ情報
  default from: "user@gmail.com"

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

    mail to: "user@sample.com", subject: "ActionMailer test"
  end
end

##メールテンプレートの編集
テンプレートの拡張子をhtml.erbにすればHTMLメール、text.erbにすればテキストメールとなる。

/views/notice_mailer/sendmail_confirm.html.erb

NoticeMailer#sendmail_confirm

<%= @greeting %>, find me in app/views/app/views/notice_mailer/sendmail_confirm.html.erb

<h2>テスト</h2>
<p>あいうえおかきくけこさしすせそたちつてとなにぬねのあいうえおかきくけこさしすせそたちつてとなにぬねのあいうえおかきくけこさしすせそたちつてとなにぬねのあいうえおかきくけこさしすせそたちつてとなにぬねのあいうえおかきくけこさしすせそたちつてとなにぬねのあいうえおかきくけこさしすせそたちつてとなにぬねの</p>

以上でActionMailerからGmailを経由して送信できるようになった。


$ rails c
NoticeMailer.sendmail_confirm.deliver

メールが送信されたかを確認。

##viewから送信

items_controller.rb

  def mail_send
    @mail = NoticeMailer.sendmail_confirm.deliver
    render :text => 'send finish'
  end

index.html.erb

<%= link_to 'Send Mail', action: "mail_send" %>

以上でviewから送信できる。

199
202
1

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
199
202

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?