如何配置 Rails ActionMailer 的主机名?
-
18-09-2019 - |
题
我正在处理一个相当传统的忘记密码电子邮件 - 我想通过电子邮件向用户发送嵌入在链接中的密码更改令牌,他们可以单击该链接来更改密码。我通过传统的 ActionMailer 发送电子邮件。
如果我使用普通的 link_to 标签
<%= link_to "click here", :controller => foo, :action => 'bar', :token => token %>
我从电子邮件中得到了一个相对链接,但毫无用处。
如果我添加
:only_path => false
, ,然后它错误地说我需要设置 default_url_options[:host]
. 。ActionController 文档暗示您可以通过重写控制器中的 #default_url_options 方法来实现这一点。当然有一个配置选项可以告诉 Rails 它的主机名是什么,而无需添加我自己的配置文件、解析它等?
解决方案
default_url_options
可从config.action_mailer
,应该在你的环境中的配置文件进行设置。
例如,在config/environments/production.rb
:
config.action_mailer.default_url_options = {
:host => 'www.yourdomain.com'
}
有关本地测试,修改config/environments/development.rb
:
config.action_mailer.default_url_options = {
:host => '127.0.0.1',
:port => 3000
}
然后,假设你叫一个名为路线forgot_password_login
,你可以使用这样的事情产生在你的邮件登录链接网址:
forgot_password_login_url(:token => 'a7s8q15sk2...')
其他提示
您可能希望设置:协议=> 'https' 时,以及,顺便说一句
config.action_mailer.default_url_options = {
:host => "portal.example.com",
:protocol => 'https'
}
还有另一种选择,如中所述 http://pivotallabs.com/how-i-leaned-to-stop-hating-and-love-action-mailer/
该解决方案的优点是不需要任何配置(因此不那么麻烦),并且只要您从控制器内发送电子邮件就可以正常工作。
但是,如果您打算在不通过控制器的情况下发送电子邮件(例如从命令行或响应另一封电子邮件),您需要静态配置。
设置default_url_options
直接在滑轨3.1弃用。使用 url_for 代替。
添加参数:protocol
覆盖默认值(HTTP),:protocol => 'https://'
。这将创建一个URL开始以 “https:// ...”,而不是默认的 “http://”
有趣的是,我有同样的问题,因为你这样做,但在单元测试(在遵循迈克尔·哈特尔的railstutorial)。我曾在我的test.rb文件这一行,但是这并没有帮助:
config.action_mailer.default_url_options = { host: 'example.com', protocol: 'http' }
我还添加另一条线中像下面这样test.rb,并且令人惊讶地解决了这个问题
default_url_options = { host: 'example.com', protocol: 'http' }
设置default_url_options直接在滑轨弃用3.1
使用url_for助手来创建它:
<%= link_to "click here", url_for(:controller => foo, :action => 'bar', :token => token, :host => 'www.yourdomain.com') %>
您可以做
<%="click here", :controller => foo, :action => 'bar', :token => token, :host=>request.host -%>