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

邮差的信 提交于 2019-11-27 14:03:28

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"

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.

You can use this code which is much cleaner and simpler

# app/mailers/my_mailer.rb
class MyMailer < Devise::Mailer
  def headers_for(action, opts)
    backup_email = "..."
    super.merge!({bcc: backup_email})
  end
end

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

With Hash passed to merge! method you can add or modify any email headers you'd like.

Your answer worked for me. Thank you so much.

I had a scenario wherein, i was required to customize devise to: 1) send signup confirmation emails in BCC to different emails based on environment. 2) emails should be added to BCC only for signup confirmation mails.

To achieve that, i compared values for action argument, like shown in the code snippet below:

def headers_for(action)
  if action == :confirmation_instructions
    if Rails.env.production?
        recipient_email = "user1@example.com"
    else
        recipient_email = "user2@example.com"
    end

    headers = {
      :subject => translate(devise_mapping, action),
      :from => mailer_sender(devise_mapping),
      :to => resource.email,
      :bcc => recipient_email,
      :template_path => template_paths
    }
  else
    super
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!