Rails : Devise : Send different Emails for Confirmation and Reconfirmation

If you have a requirement that demands to send email when every time superuser or the user him/her self changes/updates the email. Moreover you may also want to send two different email template for two scenarios.

Configure Re-Confirmable

To configure reconfirmable module, see this link.

Configure to have multiple email template

By default Devise do not support multiple email template for updated/created user by email as per Devise 3.4. You need to define your new Mailer inherited from Devise::Mailer and config Devise to use the Mailer you defined.

# in app/mailers/my_devise_mailer.rb
class MyDeviseMailer < Devise::Mailer
  layout 'mailers'
 
  # To make sure that your mailer uses the devise views
  default template_path: 'devise/mailer' 

 def confirmation_instructions(record, token, options={})
   # Use different e-mail templates for signup e-mail confirmation 
   #   and for when a user changes e-mail address.
   if record.pending_reconfirmation?
     options[:template_name] = 'reconfirmation_instructions'
   else
     options[:template_name] = 'confirmation_instructions'
   end
   super
  end
end

and

 # in config/initializers/devise.rb

 # Configure the class responsible to send e-mails.
 # config.mailer = 'Devise::Mailer'
 config.mailer = 'MyDeviseMailer'

 Alternative way to configure mailer

# Devise Mailer

def confirmation_instructions(record)
  @resource = record
    if @resource.pending_reconfirmation?
      mail(to: @resource.unconfirmed_email, subject: "Confirm new email") do |format|
        format.html { render ... }
      end
    else
      mail(to: @resource.email, subject: "Confirm new account") do |format|
        format.html { render .... }
      end
    end
end

Sources:

http://stackoverflow.com/questions/15770070/how-to-send-two-different-emails-for-devise-confirmable-and-devise-reconfirmable

https://cbabhusal.wordpress.com/2015/09/25/ruby-on-rails-devise-re-confirmable-importances-and-usages/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s