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

devise, registration, ruby-on-rails

Solution

One way to do it would be to override the `headers_for` action in Devise::Mailer

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

And tell devise to use your mailer:

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

Problem

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`.

Original source