Skip to content

Notify users via email when their passwords change

Moncef Belyamani edited this page Mar 28, 2015 · 7 revisions

For security purposes, sometimes you need to notify users when their passwords change. The following code has been tested with Rails 4.1.5 and Devise 3.4.1, assuming your Devise model is named User.

To do so, you need to generate a new mailer. Let's call it UserMailer:

rails g mailer user_mailer password_changed

Add some code:

# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
  default from: "[email protected]"

  def password_changed(id)
    @user = User.find(id)
    mail to: @user.email, subject: "Your password has changed"
  end
end

Then add some content to the email template:

<% #app/views/user_mailer.html.erb %>
<h2>Your password has changed</h2>
<hr>
<p>Hi <%= @user.email %>,</p>
<p>We wanted to let you know that your password was changed.</p>

Now configure your model:

# app/models/user.rb
class User < ActiveRecord::Base
  after_update :send_password_change_email, if: :encrypted_password_changed?
  
  private
   
  def send_password_change_email
    UserMailer.password_changed(id).deliver
  end
end

Voila!

Clone this wiki locally