2017-05-14 53 views
6

我不能理解关于电子邮件的一些微不足道的东西,但defaul_url_options中的主机是做什么的?我需要配置smtp设置来配置电子邮件的发送方式,但default_url_options与此有关吗?什么是ActionMailer default_url_options?

config.action_mailer.raise_delivery_errors = true 
    config.action_mailer.delivery_method = :smtp 
    host = '<your heroku app>.herokuapp.com' 
    config.action_mailer.default_url_options = { host: host } 
    ActionMailer::Base.smtp_settings = { 
    :address  => 'smtp.sendgrid.net', 
    :port   => '587', 
    :authentication => :plain, 
    :user_name  => ENV['SENDGRID_USERNAME'], 
    :password  => ENV['SENDGRID_PASSWORD'], 
    :domain   => 'heroku.com', 
    :enable_starttls_auto => true 
    } 

回答

8

default_url_options设置是在电子邮件模板构建链接的网址是有用的。通常,需要使用此配置选项设置:host(即Web服务器的完全限定名称)。它与发送电子邮件无关,它只在电子邮件中配置显示链接

需要进行设置,这是很好的记录在Rails Guides以及ActionMailer::Base sources

URLs can be generated in mailer views using url_for or named routes. Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need to provide all of the details needed to generate a URL.

When using url_for you'll need to provide the :host , :controller , and :action:

<%= url_for(host: "example.com", controller: "welcome", action: "greeting") %> 

When using named routes you only need to supply the :host

<%= users_url(host: "example.com") %> 

因此,要改写的文档,网页中,当前Web服务器的名称(在绝对使用链接)取自传入的请求信息。但是,在呈现电子邮件时(没有请求),您没有这些信息,这就是为什么您必须手动提供此信息,以便电子邮件中的链接正常工作。

1

您是否尝试过在ActionMailer模板中生成URL?如果你做了至少一次,那么你可能熟悉以下错误:

ActionView::TemplateError (Missing host to link to! Please provide :host parameter or set default_url_options[:host]) 

这是因为实例的ActionMailer没有关于传入请求的任何方面,所以你需要提供:主机, :控制器和:action :.如果您使用命名路由,ActionPack将为您提供控制器和操作名称。否则,使用url_for helper需要传递所有参数。

<%= message_url %> 
<%= url_for :controller => "messages", :action => "index" %> 

无论你的选择,你总是需要提供主机选项​​生成的ActionMailer的URL。如图中的ActionMailer指南,你基本上有两种方法主机值传递给的ActionMailer:

1. set a global value 
2. pass the option each time you generate an URL 

定义default_url_options是更好,然后通过URL每次。 这就是我们为什么这样做。

相关问题