Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ActionMailer default_url_options?

I must not understand something trivial about email but what does the host in defaul_url_options do? The need for the smtp settings make sense to me to configure how the email will be sent out but how is default_url_options relevant to that?

  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
  }
like image 766
user782220 Avatar asked May 14 '17 07:05

user782220


People also ask

What is ActionMailer?

Action Mailer allows you to send emails from your application using mailer classes and views.

What is action_ Mailer in Rails?

Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from ActionMailer::Base and live in app/mailers. Those mailers have associated views that appear alongside controller views in app/views.

How do you preview emails in Rails?

rails generates a mail preview if you use rails g mailer CustomMailer . You will get a file CustomMailerPreview inside spec/mailers/previews folder. Here you can write your method that will call the mailer and it'll generate a preview.


1 Answers

The default_url_options setting is useful for constructing link URLs in email templates. Usually, the :host, i.e. the fully qualified name of the web server, is needed to be set up with this config option. It has nothing to do with sending emails, it only configures displaying links in the emails.

The need for setting this is nicely documented in the Rails Guides as well 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") %>

So, to reword the docs, in web pages, the name of the current web server (to be used in absolute links) is taken from the incoming request info. But you don't have this information available when rendering an email (there's no request), that's why you have to provide it manually, so that links in emails work properly.

like image 187
Matouš Borák Avatar answered Oct 22 '22 01:10

Matouš Borák