rails 3 + devise: how to modify the mailer method for confirmation emails to add user's second email address

jpw picture jpw · Jun 7, 2011 · Viewed 10.4k times · Source

Background: In our app, we often have a sales rep do the setup for our customer using the salesperson's computer (often customers don't have access to their email at the time we set them up). So we're thinking to add a field to the devise registration form for the sales rep's email address and have the confirm link ALSO go to that email address.

Question: Is there a way to tell devise to bcc (or cc) the initial confirmation email (only the initial confirmation email) to an (optional) "backup_email" email address that is also provided on the new user registration form?

Alternatively, is there a way to 'disable' the confirmation email process but ONLY when a certain code is entered into the registration field?

I know how to add another field to the devise registration form, but I don't see how/where to modify the devise mailer code so when a confirmation email is sent to the "email" address it ALSO goes to the "backup_email" address (if any, sometimes it's blank).


Thanks to Johnny Grass!

I did rails generate mailer CustomerUserMailer and added

#config/initializers/devise.rb
config.mailer = "CustomUserMailer"

my custom mailer looks like:

# app/mailers/customer_user_mailer.rb
class CustomUserMailer < Devise::Mailer
  def headers_for(action)
    headers = {
      :subject       => translate(devise_mapping, action),
      :from          => mailer_sender(devise_mapping),
      :to            => resource.email,
      :cc            => resource.backup_user_email(action),
      :template_path => template_paths
    }
  end
end

Then I moved the 3 mailer templates FROM views/devise/mailer to views/customer_user_mailer (otherwise the emails are empty)

Then I added a method to my User model called backup_user_email() that returns the 'backup' email address (if any) based on the data in the user record and the action. The only "trick" there is that when testing the action it is not action == "confirmation_instructions" it is action == :confirmation_instructions.

Answer

Bryce picture Bryce · Feb 5, 2013

Just in case anyone got here through Google - in the latest version of Devise, header_for takes two parameters. So your code would need to be:

class MyMailer < Devise::Mailer
  backup_email = "..."
  def headers_for(action, opts)
    headers = {
      :subject       => subject_for(action),
      :to            => resource.email,
      :from          => mailer_sender(devise_mapping),
      :bcc           => backup_email,
      :reply_to      => mailer_reply_to(devise_mapping),
      :template_path => template_paths,
      :template_name => action
    }.merge(opts)
  end
end

That might not be the best way to do it, but at least it avoids errors.