LoginSignup
1
0

More than 3 years have passed since last update.

padrinoでgmailにメール送信

Last updated at Posted at 2019-02-17

padrinoでメールを送信する方法をざっくりメモ

前提条件

・googleアカウントでアプリパスワードを発行していること
・action_mailerを導入済み

コード例

mail.rb
require 'action_mailer'

ActionMailer::Base.prepend_view_path File.expand_path('./app/views/mailers')
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com',
  domain: 'gmail.com',
  port: 587,
  user_name: 'your_gmail_account',
  password: 'google_app_password',
  authentication: 'plain',
  enable_starttls_auto: true
}

class SampleMailer < ActionMailer::Base
  def template_example(inquiry)
    @inquiry = inquiry
    mail(
      to: 'hogehoge@gmail.com',
      from: 'test@example.net',
      subject: 'test', &:text
    )
  end
end

説明

独自に設定が必要な箇所のみ説明

mail.rb
ActionMailer::Base.prepend_view_path File.expand_path('./app/views/mailers')

メールテンプレートが配置されているディレクトリのパスを設定。
設定したディレクトリに存在するクラス名に応じたディレクトリから
メソッド名に応じたviewファイルを探し出す。

上のコードでは
./app/views/mailers
の配下に

mail.rb
class SampleMailer < ActionMailer::Base
  def template_example(inquiry)

クラス名に対応したディレクトリ
sample_mailerを作成し

sample_mailer配下に
template_example.text.erbを作成する

mail.rb
ActionMailer::Base.smtp_settings = 

user_nameにgoogleアカウント名
passwordに発行したアプリパスワード
他はコピペでOK

mail.rb
class SampleMailer < ActionMailer::Base
  def template_example(inquiry)
    @inquiry = inquiry
    mail(
      to: 'hogehoge@example.jp',
      from: 'test@example.net',
      subject: 'test', &:text
    )
  end
end

あとはto:に自分のメールアドレスを設定してやって
適当な箇所でインスタンス変数を渡してメソッドを使ってやれば
メールが送信されるはず。

1
0
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
1
0