ruby-on-railsrubyruby-on-rails-5

Dynamic default from with Action Mailer Rails


Is it possible in Rails to set the default from in Action Mailer from an attribute in a Model, without having to set it every time in the actions?

I have a multi tenant app, with different tenants having different emails which has to be the default from in the mailer.

As per the Docs,

    default to:       -> { 'user@email.test' },
    from:     -> { method_that_retrieves_tenant_email }

should be possible, but when I try that, It throws the following error

    Failure/Error: from:     -> { method },
    ArgumentError:
    wrong number of arguments (given 1, expected 0)

I am using Rails 5.2.0 & ruby 2.3.1p112.

Additional Details: This is what I have used

    class ApplicationMailer < ActionMailer::Base 
      default from: -> { tenant_email }
      .....

      private
      def tenant_email
        fetch_email
      end

Solution

  • Just found out that this works.

        class ApplicationMailer < ActionMailer::Base
    
          after_action :set_default_from
    
        private
    
        def set_default_from
          mail.to = tenant_email
        end