/ rails

Rails : Devise : Send different Emails for Confirmation based on the presence of attribute or parameter

So what am I up to today? - I thought of scribbling down some pieces of code that I wrote to help one of my interns in my company to help complete a task.

I was juggling with my daily work and I suddenly got a ping in our slack team

Hey can you please advise me on how to use separate mailer templates for devise confirmation instructions just based on the presence/absence of a parameter/attribute value ?

I thought for a second and said,

TL;DR: you need to tell devise to your custom mailer, override the confirmation_instructions method in the same and you can pass in the template you want to use as options to that method.

Now the long story for who needs step by step instructions.

If you have a requirement that demands to send email when every time a user signup by his own or a user is invited into the system by an existing user and you may also want to send two different email template for two scenarios.

By default Devise do not support multiple email template so you need to define your new Mailer inherited from Devise::Mailer and configure Devise to use the Mailer you defined.

Configuring devise to use custom Mailer
# in config/initializers/devise.rb

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

and go ahead and create your CustomMailer inherited from Devise::Mailer

# in app/mailers/custom_devise_mailer.rb
class CustomDeviseMailer < 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 normal signup e-mail confirmation 
   # and for when a user is invited into the system by an existing user.

   if record.invited?
     options[:template_name] = 'invited_confirmation_instructions'
   else
     options[:template_name] = 'confirmation_instructions'
   end
   super
  end
end

I hope someone finds this useful.

Manu S Ajith

Manu S Ajith

Tech Entrepreneur, dating Elixir, in long-term ❤️ w/ Ruby, had multiple one night stands w/ Go. Into functional paradigms DDD/CQRS/EventSourcing architecture these days. @manusajith on the interwebs

Read More