LoginSignup
13
14

More than 5 years have passed since last update.

Rails&Heroku / Gmailを使わないでユーザーに一斉メール送信する

Posted at

ブログを更新しました。元の記事はコチラ


Railsアプリからウェブサイトの登録ユーザー宛に、メールを送信する際に、Gmailを使ったらそっこうでアカウントをロックされたので、別の手段を取ることに。

Gmailは、自分のログインしたことのない場所で、何者かがログインを試みようとすると警告を出してきます。よく海外を移動する身としては、毎回確認されてイラっとすることも。クレジットカード会社も同じようなことをやってますよね。
  
で、今回はRailsアプリからGmail経由でメール送信しようと思ったんですが、Heroku(ヨーロッパリージョン)に乗っているので、ヨーロッパから大量の不正ログインがあったと判断され、強制的にパスワードのリセットを求められました。
Gmailの親切機能ですが、アプリで使うのは無理だ…ということで他の方法は…
  
普通にHerokuのadd-onに選択肢がけっこうありますね。
  

Mandrill

あのMailChimpによって提供されているのは、Mandrillというadd-on。
12,000通/月まで無料です。
今のところ十分なので、これでいくことにしました。

自分のアプリにadd-onを追加すると、SMTPユーザーネームとSMTPパスワードが取得できるので、それを使って、Railsを設定。

config/environments/production.rb  


  # For Mandrill
  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address   => "smtp.mandrillapp.com",
    :port      => 587, 
    :enable_starttls_auto => true,
    :user_name => "appxxxxxxxxxx@heroku.com",
    :password  => "xxxxxxxxxxxxxxxxxxxxx", 
    :authentication => 'login', 
    :domain => 'heroku.com', 
  }

これでサクッとメールが送信できる。
controllerやmailerの処理は基本変えなくていいんですが、一点だけ、変更しないとメールが送られなかったので、メモ。

mailers/your_mailer.rb


class YourMailer < ActionMailer::Base

  def my_mail(user)
    @user = user
    begin
      mail to: user.email,
           subject: "#{user.name}さん、こんにちは!",
           from: "xxxx@yourdomain.com"
    rescue => e
      puts "エラー : #{e.message}"
    end
  end
end

from: "xxxx@yourdomain.com" を省略すると、メールが送られなかった。

  
以上です。
開封率なんか自動で収集してくれるので、とても便利。

Screen Shot 2014-05-28 at 1.36.35 PM

http://workabroad.jp/posts/2093

13
14
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
13
14