To send email from Rails in production, set config.action_mailer.delivery_method = :smtp and fill config.action_mailer.smtp_settings with your server's address, port, user name, password and authentication type in config/environments/production.rb. Use port 587 with STARTTLS or port 465 with implicit TLS, store the credentials in Rails credentials or environment variables, set default_url_options so links in emails are correct, and send with deliver_later so requests do not wait on the SMTP server.
This guide gives a production-ready configuration, then covers mailers, attachments, background delivery, previews and the failures you are most likely to meet. A shorter walk-through focused on background jobs is in Action Mailer with deliver_later.
Production configuration
# 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.perform_caching = false
config.action_mailer.default_url_options = { host: "app.example.com", protocol: "https" }
config.action_mailer.smtp_settings = {
address: ENV.fetch("SMTP_HOST"),
port: Integer(ENV.fetch("SMTP_PORT", "587")),
domain: "example.com", # HELO/EHLO name
user_name: Rails.application.credentials.dig(:smtp, :user_name) || ENV["SMTP_USER"],
password: Rails.application.credentials.dig(:smtp, :password) || ENV["SMTP_PASS"],
authentication: :plain,
enable_starttls_auto: true,
open_timeout: 10,
read_timeout: 30
}
endEach setting has a reason. raise_delivery_errors = true makes failures raise exceptions, which your job backend can retry; with it off, errors are swallowed silently. default_url_options is required for URL helpers in mailer views, because a mailer has no request to infer the host from; forgetting it produces a "Missing host to link to" error. domain is the name the client announces in EHLO and should be a real domain you control. The two timeouts stop a stalled server from tying up a worker; Ruby's defaults are long. Settings for the underlying library change across versions, so confirm them against the guide for your Rails version.
Choose the port and TLS mode
| Port | Mode | Settings |
|---|---|---|
| 587 | STARTTLS: connect in plain text, then upgrade | port: 587, enable_starttls_auto: true |
| 465 | Implicit TLS: encrypted from connect | port: 465, tls: true (do not combine with STARTTLS) |
| 25 | Server to server, often blocked | Avoid for application submission |
Use 587 unless your provider documents otherwise; see SMTP settings, ports and authentication for the trade-offs. The authentication value must be one the server offers: :plain and :login are the usual ones, both safe because TLS protects them, and :cram_md5 is rare. Avoid openssl_verify_mode: OpenSSL::SSL::VERIFY_NONE; it silences certificate errors by removing the protection, and the right fix is the correct host name or CA bundle.
Store credentials safely
# Edit encrypted credentials (Rails 5.2+)
bin/rails credentials:edit
# or per environment
bin/rails credentials:edit --environment production
# config/credentials/production.yml.enc content:
# smtp:
# user_name: your-username
# password: your-passwordEncrypted credentials need the master key (RAILS_MASTER_KEY or the key file) on the server, so inject that through your platform's secret store. Environment variables are equally valid on container platforms. Rotate the SMTP password if it ever appears in a log or a repository. Use a distinct credential per application so you can revoke one without affecting others.
Write a mailer
bin/rails generate mailer UserMailer welcome# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: "Example App <[email protected]>"
layout "mailer"
end
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def welcome(user)
@user = user
@url = login_url # needs default_url_options
attachments["guide.pdf"] = File.read(Rails.root.join("public/guide.pdf"))
mail(to: @user.email, subject: "Welcome to Example")
end
end
# app/views/user_mailer/welcome.html.erb and welcome.text.erb
# Provide BOTH templates; Rails sends multipart/alternativeCreate a matching .text.erb and .html.erb template for every action so each message carries a plain-text alternative. Use attachments.inline["logo.png"] for embedded images and reference them with image_tag attachments["logo.png"].url. Attachments are base64 encoded and add roughly a third to the size, so link to large files instead. Design points for readable HTML email are in email CSS support.
Send in the background
# In a controller or service
UserMailer.welcome(user).deliver_later # queued through Active Job
UserMailer.welcome(user).deliver_later(wait: 5.minutes) # delayed
UserMailer.welcome(user).deliver_now # synchronous, avoid in requestsdeliver_later enqueues a job that renders and sends the message. It is only as durable as your Active Job adapter. The default in-process :async adapter loses queued jobs on restart, so production apps should configure a real backend such as Sidekiq, Solid Queue, GoodJob or Resque through config.active_job.queue_adapter. Pass record objects to mailers (Active Job serialises them with GlobalID) rather than large values, and be aware that a deleted record causes the job to fail on deserialisation. Configure retries in your queue backend for temporary SMTP failures, and do not retry permanent rejections forever. Queue design, retries and idempotency are covered in reliable email sending design.
Preview and test
- Previews. Add a preview class under
test/mailers/previews(orspec/mailers/previewsfor RSpec) and open/rails/mailersin development to see rendered HTML and text. - Tests. In the test environment Rails uses
:testdelivery, so messages go intoActionMailer::Base.deliveries; assert on subject, recipients and body without any network. - Local SMTP. In development, point
smtp_settingsat a local catch-all server such as Mailpit or MailHog so no real recipient gets test mail. - Staging. Use interceptors (
ActionMailer::Base.register_interceptor) to rewrite recipients to a safe address outside production.
Handle failures and monitor delivery
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
# raise_delivery_errors = true means SMTP failures surface as exceptions in the job
end
# Observe every delivery
class MailLogObserver
def self.delivered_email(message)
Rails.logger.info("mail accepted by SMTP server message_id=#{message.message_id} to=#{Array(message.to).size} recipients")
end
end
ActionMailer::Base.register_observer(MailLogObserver)Failures fall into two groups. Configuration failures, such as a wrong password, a missing host or a blocked port, will not fix themselves; they should raise loudly and alert someone. Transient failures, such as timeouts and 4xx replies, should be retried by your job backend with increasing delays. Make sure your queue has a dead-letter or failed-jobs view that somebody actually watches, because with deliver_later an exception no longer reaches the user. An observer like the one above records that the SMTP server accepted a message. That is not the same as delivery: bounces arrive later, either as a message to the envelope sender or as webhook events from a delivery service, and you should record them against the user so you stop mailing dead addresses.
Add a lightweight health check as well. A scheduled job that sends a test message to a monitored mailbox every day, and alerts if it does not arrive, finds expired passwords, blocked ports and DNS mistakes before customers do. Pair it with a periodic review of your SPF and DKIM records, since a changed include or a rotated key will not announce itself in the Rails logs.
Multiple environments and from addresses
Keep the From address in one place, the default hash of ApplicationMailer, and drive the domain from configuration so staging mail cannot masquerade as production. Use an obviously different subject prefix in non-production environments, for example through an interceptor, so nobody mistakes a staging message for a real one. If different kinds of mail need different senders, such as billing receipts and product announcements, give each mailer its own default from: and, where your provider supports it, its own credentials and sending subdomain so that a problem with one stream cannot damage the other.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Net::SMTPAuthenticationError 535 | Wrong credentials, or an app password or API key is needed | Check with another client. See error 535 |
| Net::OpenTimeout or Errno::ECONNREFUSED | Port blocked, wrong host or the platform blocks outbound SMTP | Test from the server; try 587 and 465 |
| OpenSSL::SSL::SSLError, wrong version number | STARTTLS settings used on port 465 or the reverse | Use tls: true for 465 and starttls for 587 |
| OpenSSL::SSL::SSLError, certificate verify failed | Host name mismatch or old CA bundle | Use the host name on the certificate; update CA certificates |
| ArgumentError: Missing host to link to | default_url_options not set in this environment | Set host and protocol |
| Mail sent in development but not production | perform_deliveries off, wrong delivery_method or missing job worker | Check the configuration and that workers are running |
| No error but message never arrives | Accepted by the server, then bounced or filtered | Check bounce events and domain authentication |
| Duplicate emails | Job retried after the SMTP call succeeded but before acknowledgement | Make sends idempotent where possible |
Deliverability and next steps
Rails configuration gets the message to your SMTP server; whether it reaches the inbox depends on domain authentication and reputation. Before launch, publish SPF and DKIM for the From domain (see authenticating your sending domain), send a test to major providers and read the Authentication-Results header. Handle bounces and complaints by suppressing the address in your own database. If you use MigoSMTP, set the address to smtp.migosmtp.com, the port to 587 with STARTTLS or 465 with tls: true, and use your account credentials. Where outbound SMTP is blocked, an HTTP-based API is the alternative; compare them in SMTP versus API.
Run Rails mail through an authenticated relay Use MigoSMTP with the settings above and watch delivery events.
References and further reading
Frequently asked questions
How do I configure SMTP in Rails production?
Set config.action_mailer.delivery_method to :smtp and fill smtp_settings with address, port, user_name, password, authentication and TLS options in config/environments/production.rb.
Which settings do I use for port 587 and port 465?
For 587 use enable_starttls_auto: true. For 465 use tls: true for implicit TLS, and do not combine it with STARTTLS.
Why do mailer links show "Missing host to link to"?
Mailers have no request, so set config.action_mailer.default_url_options with your host and protocol.
Should I use deliver_now or deliver_later?
Use deliver_later with a durable Active Job backend so requests do not wait on SMTP. Use deliver_now only inside a background job.
Where should I store the SMTP password?
In encrypted Rails credentials or environment variables supplied by your platform, never in the repository.