如何为Rails ActionMailer配置主机名?

我正在处理一个相当传统的忘记密码电子邮件 – 我想通过电子邮件向用户发送一个密码更改令牌,该密码更改令牌嵌入在他们可以点击以更改密码的链接中。 我通过传统的ActionMailer发送电子邮件。

如果我使用普通的link_to标签

 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的命名路由,您可以使用以下内容在邮件程序中生成登录链接URL:

 forgot_password_login_url(:token => 'a7s8q15sk2...') 

你可能想设置:protocol =>’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/中所述

此解决方案的优势在于它不需要任何配置(因此不那么麻烦),并且只要您从控制器内发送电子邮件就可以正常工作。

但是,如果您计划在不通过控制器的情况下发送电子邮件(例如,从命令行或响应其他电子邮件),则需要静态配置。

在Rails 3.1中不推荐直接设置default_url_options 。 请改用url_for 。

添加参数:protocol以覆盖默认值(http) :protocol => 'https://' 。 这将创建以“https:// …”开头的url,而不是默认的“http://”

有趣的是,我遇到了和你一样的问题,但是在unit testing中(跟随Michael Hartl的轨道教程)。 我在test.rb文件中有这一行,但这没有帮助:

 config.action_mailer.default_url_options = { host: 'example.com', protocol: 'http' } 

我还在test.rb中添加了这样的另一行,令人惊讶的是,这解决了这个问题

 default_url_options = { host: 'example.com', protocol: 'http' } 

在Rails 3.1中不推荐直接设置default_url_options

使用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 -%>