17

谷歌搜索无济于事。也没有在 API 中找到任何东西。我期待某种类方法或配置选项来设置它......

所以,而不是打电话

from "my@email.com"

对于每种方法,它都可以自动调用。

4

6 回答 6

55

Rails 3

config/environments/development.rb:

ActionMailer::Base.default :from => 'default@development-server.com'

config/environments/production.rb:

ActionMailer::Base.default :from => 'default@production-server.com'

You can also set this per mailer:

class MyMailer < ActionMailer::Base
  default :from => 'default@myapp.com'
end

Rails 2

This is not supported by default. But you can achieve this functionality by using the action_mailer_callbacks plugin. Essentially this plugin allows you to add before and after filters for the deliver method.

class FooMailer < ActionMailer::Base
  before_deliver do |mail|
    mail.from = "abc@xyz.com"
  end

end

Reference:

1) Article discussing the plugin.

OR

You can monkey patch the from method of ActionMailer::Base.

Add the code below to your config\initializers\mail.rb

class ActionMailer::Base
  class_inheritable_hash :default
  def from_with_default(input=nil)
    return from_without_default(input) || default[:from] if input.nil?
    from_without_default(input)
  end
  alias_method_chain :from, :default
end

Now you can configure your default value as follows:

config/environments/development.rb:

ActionMailer::Base.default = {:from => 'default@development-server.com'}

config/environments/production.rb:

ActionMailer::Base.default = {:from => 'default@production-server.com'}

You can also set this per mailer:

class MyMailer < ActionMailer::Base
  self.default = {:from => 'default@myapp.com'}
end
于 2010-03-15T05:09:37.263 回答
23

在 Rails 4 中,您可以在您的环境中进行设置:

config.action_mailer.default_options = {
  :from => "foo@bar.com"
}
于 2012-09-26T20:28:46.353 回答
11

在 Rails 3 中:

配置/环境/development.rb:

ActionMailer::Base.default :from => 'default@development-server.com'

配置/环境/production.rb:

ActionMailer::Base.default :from => 'default@production-server.com'
于 2010-07-19T21:08:49.193 回答
0

我采用了 KandadaBoggu 建议的猴子修补方法。但是,它在 Rails 2.3.8 中不能正常工作。你不能覆盖默认值。但是,这有效:

def from_with_default(input=nil)
  return instance_variable_set("@from", input) unless input.nil?
  from_without_default || FROM_EMAIL
end
alias_method_chain :from, :default
于 2010-10-29T16:56:18.777 回答
0

红宝石 5 & 6

config/environments/$RAILS_ENV.rb
config.action_mailer.default_options = {来自:'no-reply@example.com'}

于 2020-04-03T15:58:18.647 回答
-1

.. rails-6 有变化吗?

config.action_mailer.default_options = { from: 'noreply@xxx.xx' }

不在生产中工作.rb

于 2020-03-28T15:29:27.357 回答