New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 26 Oct 2026

Ruby on Rails Action Mailer: SMTP Configuration, deliver_later and Troubleshooting

Set up Rails Action Mailer with SMTP using encrypted credentials, build multipart mailers and previews, send in the background with deliver_later, and diagnose authentication, TLS and URL errors.

EB
Written by Ethan Brooks
Transactional Email Specialist
Reviewed by Karan Malhotra
  • Published9 Jun 2026
  • Read time7 min
  • Length1,495 words
Share this guide

Action Mailer is the part of Rails that builds and delivers email. A mailer looks like a controller: each method is an action, each action has views, and calling it produces a message you can deliver now or later. The delivery itself is configured separately, per environment, and for production you almost always want SMTP through a relay that authenticates your domain. This guide shows how to configure smtp_settings, keep the credentials in encrypted credentials or environment variables, write a multipart mailer with attachments, preview it in the browser, send in the background with deliver_later, and fix the errors that appear most often. The examples use placeholders. Take real values from your SMTP provider's dashboard.

Configconfig.action_mailer.delivery_method = :smtp and smtp_settings
SecretsRails credentials or environment variables, never the repo
Senddeliver_later through Active Job
CheckPreviews at /rails/mailers and logs in development

Configure SMTP per environment

Delivery settings live in the environment files. In config/environments/production.rb set the delivery method and the SMTP details. Read the secrets from credentials or the environment.

# config/environments/production.rb
Rails.application.configure do
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_url_options = { host: "app.example.com", protocol: "https" }

  config.action_mailer.smtp_settings = {
    address:              ENV.fetch("SMTP_HOST"),
    port:                 587,
    user_name:            Rails.application.credentials.dig(:smtp, :user_name),
    password:             Rails.application.credentials.dig(:smtp, :password),
    authentication:       :plain,
    enable_starttls_auto: true,
    open_timeout:         10,
    read_timeout:         20
  }
end

A few settings deserve attention. address and port must match the encryption you intend to use: port 587 with STARTTLS, which Rails enables automatically when the server offers it, or port 465 with implicit TLS, for which you set tls: true. authentication is normally :plain or :login; check what your provider supports. Always set open_timeout and read_timeout, because the default behaviour on a blocked port is to wait. Finally, raise_delivery_errors = true makes failures visible instead of silently dropping them; in production, send those exceptions to your error tracker. If you are unsure about the port, read which SMTP port to use.

Store credentials safely

Do not commit passwords. Use Rails encrypted credentials: run bin/rails credentials:edit and add the values, or use environment variables set by your deployment platform. The encrypted file is safe to commit, but the master key is not, so keep config/master.key out of version control and give it to production through the RAILS_MASTER_KEY variable. If a production deploy sends nothing and logs show authentication errors, the first thing to check is that the master key is present and that the process reads the same values you tested with. When a login fails with a 535 reply, see SMTP error 535.

Set default_url_options

Links inside emails must be absolute, because the message is read outside your site. Rails cannot guess the host, so set default_url_options in each environment, and use _url helpers, not _path helpers, inside mailer views. A missing host is the cause of the error "Missing host to link to! Please provide the :host parameter". In development you can use localhost with a port; in production use your real domain and https.

Create a mailer

Generate a mailer and add an action. Set the defaults at the top of the class, and use mail() in the action.

# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: "Example App <[email protected]>"
  layout "mailer"
end

# app/mailers/order_mailer.rb
class OrderMailer < ApplicationMailer
  def shipped(order)
    @order = order
    attachments["invoice-#{order.number}.pdf"] = order.invoice_pdf
    mail(
      to: order.customer.email,
      subject: "Your order #{order.number} has shipped",
      reply_to: "[email protected]"
    )
  end
end

Create two views, shipped.html.erb and shipped.text.erb, in app/views/order_mailer/. When both exist, Rails builds a multipart message with a text part and an HTML part automatically. That is the right default: clients that cannot display HTML use the text, and filters tend to trust messages that include both. Use inline styles and table-based layout in the HTML, because many clients ignore external CSS. Our HTML email template guide lists what renders reliably.

Deliver now or later

Calling OrderMailer.shipped(order).deliver_now sends the message in the current process. Calling deliver_later enqueues an Active Job that sends it from a worker. Prefer deliver_later for almost everything that is not part of an interactive flow, because an SMTP conversation can take several seconds and you do not want a slow server to slow down a request.

OrderMailer.shipped(order).deliver_later
OrderMailer.shipped(order).deliver_later(wait: 10.minutes)

Pass the record, and Rails serialises it with GlobalID so that the worker loads a fresh copy. If the record is deleted before the job runs, the job raises ActiveJob::DeserializationError; decide whether to discard that error. Configure a real queue adapter in production, such as Solid Queue, Sidekiq or another adapter, because the default inline or async adapters do not survive a restart. Make jobs safe to retry, and use the pattern from rate limits, retries and backoff to separate temporary from permanent failures. One more rule helps: enqueue after the database transaction commits, by calling deliver_later in an after_commit callback, so that the worker never runs before the record exists.

Preview and test mailers

Rails can render a mailer in the browser without sending it. Add a preview class under test/mailers/previews or spec/mailers/previews, then open /rails/mailers in development. For automated tests, use the test delivery method, which stores messages in ActionMailer::Base.deliveries:

class OrderMailerPreview < ActionMailer::Preview
  def shipped
    OrderMailer.shipped(Order.first)
  end
end

# test
assert_emails 1 do
  OrderMailer.shipped(order).deliver_now
end
assert_equal ["[email protected]"], ActionMailer::Base.deliveries.last.to

In development you can use a tool that catches mail locally, or set the delivery method to :file so messages are written to tmp/mails. To confirm that a real SMTP account works before wiring it in, use the steps in how to test an SMTP connection.

Interceptors, observers and per-mailer settings

Action Mailer lets you hook into delivery without touching each mailer. An interceptor runs before a message is handed to the delivery method, which makes it the right place to stop real mail in staging: register one that rewrites every recipient to a test inbox, or that prefixes the subject with the environment name. An observer runs after delivery and is useful for recording that a message was handed off. You can also give one mailer its own delivery settings by passing delivery_method and delivery_method_options to mail(), for example to send billing receipts through a different account from product notifications. Use that option sparingly, since every extra account is another set of credentials to rotate and another domain to authenticate.

Staging deserves extra care. A staging copy of production data often contains real customer addresses, and a single forgotten test run can mail them. Use an interceptor that refuses to deliver outside the environment unless the recipient is on an allowed domain, and keep staging on a separate SMTP account with a low limit, so the damage from a mistake stays small.

Common errors and fixes

SymptomLikely causeFix
Net::SMTPAuthenticationError: 535Wrong credentials, wrong authentication type, or credentials not loaded in productionCheck the master key and values; try :login if :plain fails
Net::OpenTimeout or Errno::ECONNREFUSEDWrong host or port, or outbound SMTP blockedTest the port from the server and ask the host to open it
OpenSSL::SSL::SSLError: wrong version numberTLS mode does not match the portUse STARTTLS with 587, or tls: true with 465
Missing host to link todefault_url_options not set for this environmentSet the host and protocol, and use _url helpers
Mail is not sent in a jobQueue adapter or worker is not runningStart the worker and check the queue
No error, but no mailperform_deliveries is false, or the message went to spamCheck settings, then follow the spam checklist
Special characters broken in a subjectEncoding assumptions in custom codeLet Mail handle encoding and keep the source in UTF-8

Deliverability for Rails apps

A correct mailer is only part of delivery. Authenticate the domain in your From address with SPF, DKIM and DMARC, following the guide on authenticating your sending domain. Keep transactional mail such as password resets and receipts on a separate subdomain from marketing mail, so a campaign problem cannot delay a reset code. Send to confirmed addresses, handle bounces and complaints from your provider by removing the address from future sends, and rate-limit public forms that trigger email, since an open endpoint can be abused to send mail in your name. Keep unsubscribe links in marketing mail and make them work.

Connect Rails to a managed SMTP relay Use the host and credentials from your dashboard and send a first message in minutes.

Explore the SMTP relay

References and further reading

Frequently asked questions

Where do I configure SMTP in Rails?

In the environment file, for example config/environments/production.rb, using config.action_mailer.delivery_method = :smtp and config.action_mailer.smtp_settings.

What is the difference between deliver_now and deliver_later?

deliver_now sends in the current process. deliver_later enqueues an Active Job so that a worker sends the message, which keeps requests fast.

Why does Rails say Missing host to link to?

Mailer views need an absolute URL. Set config.action_mailer.default_url_options with a host and protocol, and use _url helpers.

How do I preview a mailer in Rails?

Add a class that inherits from ActionMailer::Preview and open /rails/mailers in development.

How should I store the SMTP password in Rails?

Use encrypted credentials or environment variables, and keep the master key out of version control.

Topics#ruby#rails#action mailer#smtp#developers
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales