开发者

How to set the ActionMailer default_url_options's :host dynamically to the request's hostname?

I am trying to set the :host for action mailer default url opti开发者_开发百科ons.

I have the below set in all the environment files

config.action_mailer.default_url_options = {
  :host => "localhost"
}

I want to make it more dynamic by providing the request host.

when I try to set it by

config.action_mailer.default_url_options = {
  :host => request.domain
}

OR

config.action_mailer.default_url_options = {
  :host => request.env["SERVER_NAME"]
}

It throws error... doesn't recognize "request" object

is there any way I can set this to the request host, not by hardcoding...?


It is also possible to set a default host that will be used in all mailers by setting the :host option in the default_url_options hash

in an application_controller.rb add:

class ApplicationController < ActionController::Base
  def default_url_options
    { host: request.host_with_port }
  end
end

Source: https://edgeguides.rubyonrails.org/action_controller_overview.html#default-url-options

Alternatively, you can pass the request when calling the mailer function from the controller

class UserMailer < ActionMailer::Base

  def welcome_email(user, request)
    @user = user
    @url  = user_url(@user, host: request.host_with_port ) # do this for each link
    mail(:to => user.email, :subject => "Welcome to My Awesome Site")
  end
end

Source : https://guides.rubyonrails.org/action_mailer_basics.html#generating-urls-with-named-routes


UPDATE: use the selected response, since this isn't thread safe.

You can create a default filter like this:

# application_controller.rb
before_filter :mailer_set_url_options

...

def mailer_set_url_options
  ActionMailer::Base.default_url_options[:host] = request.host_with_port
end

(source: http://www.cherpec.com/2009/06/missing-host-to-link-to-please-provide-host-parameter-or-set-default_url_optionshost/)


the problem is these are initializers, they are run when the rails stack loads, and not when you call active mailer.

but you don't have to use the default_url, you can just pass the hostname into the url_for/named routes in each of your mailer views. The default just avoids having to do that.

see http://api.rubyonrails.org/classes/ActionMailer/Base.html section on generating urls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜