Asnad Atta
Asnad Atta

Reputation: 4003

Confirmation instruction on other email with devise

I have two email fields in my model :email and :representative_email I want to send confirmation instructions email on :representative_email (if present or not nil) rather than :email how can I do it with efficiently. And I still want to login with my :email field.

Upvotes: 0

Views: 379

Answers (2)

Asnad Atta
Asnad Atta

Reputation: 4003

I needed to override headers_for method for devise within mailer

class DeviseCustomMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer'
  def headers_for(action, opts)
    headers = {
      subject: subject_for(action),
      to: resource.notification_email_for(action), #I changed this line
      from: mailer_sender(devise_mapping),
      reply_to: mailer_reply_to(devise_mapping),
      template_path: template_paths,
      template_name: action
    }.merge(opts)

    @email = headers[:to]
    headers
  end
end

and in my user.rb

def notification_email_for(action)
  (self.company? && self.authorised_representative && action == :confirmation_instructions) ? self.representative_email : self.email
end

and in my config/initializers/devise.rb

config.mailer = 'DeviseCustomMailer'

that's it

Upvotes: 0

Theo Chirica
Theo Chirica

Reputation: 4516

You can create a custom mailer see how to do that, and set the email you want to send to in there. That is the cleanest solution I could think of, and in the future if you want to change anything you can change it in one place only.

Upvotes: 1

Related Questions