kashif
kashif

Reputation: 1147

Dynamic Devise Sender email address

In User model, each user belong to different domain/host. I want to set it to be different from address on the basis of user's domain. Can I set this in User model somewhere, or how can I make the senders address dynamic according to user's domain.

We set devise default sender address in app/config/initializer/devise.rb like

Devise.setup do |config|
  config.mailer_sender = SOME EMAIL ADDRESS
end

Upvotes: 7

Views: 4184

Answers (3)

kross
kross

Reputation: 3753

I bumped into this because I wanted to pull the from address from I18n, but the initializer was running before I18n was setup. This was the simplest solution for me:

config.mailer_sender = Proc.new { I18n.t('mailers.from') }

Upvotes: 10

wspruijt
wspruijt

Reputation: 1067

To use the Mailer helper functions by Devise, extend the devise mailer, and override the methods/mails that need a different dynamic sender:

class CustomDeviseMailer < Devise::Mailer
  def confirmation_instructions(record, token, opts={})
    @token = token
    opts[:from] = "Dynamic Sender <[email protected]>"
    devise_mail(record, :confirmation_instructions, opts)
  end
end

And configure it in you devise.rb:

config.mailer = "CustomDeviseMailer"

Note: If you don't need a dynamic sender, just define the sender in devise.rb:

config.mailer_sender = "Static sender <[email protected]>"

Upvotes: 2

Henry
Henry

Reputation: 1055

you can set the mail.from per email basis

class UserMailer <ActionMailer::Base

def notification_email(user)
  mail(to:[email protected], from:user.email, ...)
end

That will override your default settings.

I think you can change this settings in config/initializers/devise.rb

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

to your customized mailer.

Upvotes: 1

Related Questions