ruk·si

🛤️ Ruby on Rails
Mailers

Updated at 2016-01-06 22:45

Name the mailers SomethingMailer. Without the Mailer suffix it isn't immediately apparent what's a mailer and which views are related to the mailer.

Provide both HTML and plain-text view templates.

Enable errors raised on failed mail delivery in your development. The errors are disabled by default.

# config/environments/development.rb
config.action_mailer.raise_delivery_errors = true

Use a local SMTP server like Mailcatcher in the development environment.

# config/environments/development.rb
config.action_mailer.smtp_settings = {
  address: "localhost",
  port: 1025,
  # ...
}

Provide default settings for the host name.

# config/environments/development.rb
config.action_mailer.default_url_options = { host: "#{local_ip}:3000" }

# config/environments/production.rb
config.action_mailer.default_url_options = { host: "your_site.com" }

# in your mailer class
default_url_options[:host] = "your_site.com"

Always use the _url methods in emails. Not _path methods. Paths don't contain the domain.

# bad
You can always find more info about this course
<%= link_to "here", course_path(@course) %>

# good
You can always find more info about this course
<%= link_to "here", course_url(@course) %>

Format the from and to addresses properly.

# in your mailer class
default from: "Your Name <info@your_site.com>"

Make sure that the email delivery method for your test env is test:

# config/environments/test.rb
config.action_mailer.delivery_method = :test

The delivery method for development and production should be smtp.

# config/environments/development.rb, config/environments/production.rb
config.action_mailer.delivery_method = :smtp

When sending html emails all styles should be inline. Some email clients have problems with loading files. Check out premailer and roadie.

Sending emails while generating page response should be avoided. t causes delays in loading of the page and request can timeout if multiple email are sent. To overcome this emails can be sent in background process with the help of sidekiq gem.

Sources