Skip to content

How To: Mass password reset and email notification

Leonardo Faria edited this page Feb 18, 2016 · 11 revisions

This code help you to assign a random password for each user and send a email notification to them:

source: https://gist.github.com/leonardofaria/d2eab320056a9f93a3f3

# Assign an new random password for each user and send them a email notification
# path: lib/tasks/devise.rake

namespace :device do
  desc "Mass password reset and send email instructions"
  task mass_password_reset: :environment do
  	model = ENV['MODEL'] || 'User'
  	begin
  	  model_mailer = "#{model}Mailer".constantize
  	  model = model.constantize

  	  model.where(id: 1).each do |record|
  	  	raw, enc = Devise.token_generator.generate(model, :reset_password_token)

	  	  record.reset_password_token = enc
	  	  record.reset_password_sent_at = Time.now.utc
	  	  record.save

  	    # Send change notification (Ensure you have created #{model}Mailer e.g. UserMailer)
  	    model_mailer.password_reset(record, raw).deliver_now
  	  end
  	rescue Exception => e
  	  puts "Error: #{e.message}"
  	end
  end
end

And create the mailer:

# Send password reset notification
# path: app/mailers/user_mailer.rb
# Send password reset notification
# path: app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
  default :from => "[email protected]"

  def password_reset(user, token)
    @resource = user
    @token = token
    mail(:to => user.email,
         :subject => 'Password Reset Notification')
  end
end

This is the mail template:

<p>Hello <%= @resource.email %>!</p>

<p>Someone has requested a link to change your password. You can do this through the link below.</p>

<p><%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %></p>

<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>
Clone this wiki locally