Frameworks

How to send email with Rails Action Mailer

Short answer

Rails sends email with Action Mailer. Generate a mailer with bin/rails generate mailer, write HTML and text views, and deliver it with deliver_later so Active Job sends it in the background. For SMTP, set config.action_mailer.delivery_method = :smtp and smtp_settings with the address, port, user_name, password and STARTTLS. You can also call an email API with Net::HTTP. Verify your sending domain first.

Last checked 16 November 2026

Rails sends email with Action Mailer. A mailer is a class with one method per email, each with HTML and text views, and you deliver it with deliver_later so Active Job sends it in the background. Action Mailer delivers over SMTP by default once you configure it. If you prefer an email API, you can call one with Ruby’s standard library instead. The examples below follow the Rails 8.1 guides.

Generate a mailer

bin/rails generate mailer User welcome_email

This creates app/mailers/user_mailer.rb, views under app/views/user_mailer/, and a preview class. Fill in the method:

# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  default from: "Acme <hello@acme.com>"

  def welcome_email
    @user = params[:user]
    @login_url = login_url
    mail(to: @user.email, subject: "Welcome to Acme")
  end
end

Write both views. Rails sends them together as a multipart email:

<%# app/views/user_mailer/welcome_email.html.erb %>
<p>Hi <%= @user.name %>,</p>
<p>Your account is ready. <%= link_to "Sign in", @login_url %>.</p>
<%# app/views/user_mailer/welcome_email.text.erb %>
Hi <%= @user.name %>,

Your account is ready. Sign in: <%= @login_url %>

URL helpers in mailers need a host. Set it per environment:

config.action_mailer.default_url_options = { host: "acme.com", protocol: "https" }

Deliver it

UserMailer.with(user: @user).welcome_email.deliver_later

deliver_later enqueues an Active Job. Rails 8 apps use Solid Queue by default, so make sure its worker is running in production. Use deliver_now only in scripts or jobs that are already in the background.

Attachments

def invoice_email
  @invoice = params[:invoice]
  attachments["invoice-#{@invoice.number}.pdf"] = File.read(@invoice.pdf_path)
  mail(to: @invoice.email, subject: "Invoice #{@invoice.number}")
end

Option 1: Action Mailer over SMTP

Store the key in encrypted credentials:

bin/rails credentials:edit
mailcandor:
  key: mc_live_xxxxxxxxxxxxxxxx

Then configure SMTP in config/environments/production.rb:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:         "smtp.mailcandor.com",
  port:            587,
  domain:          "acme.com",
  user_name:       "mailcandor",
  password:        Rails.application.credentials.dig(:mailcandor, :key),
  authentication:  "plain",
  enable_starttls: true,
  open_timeout:    5,
  read_timeout:    5
}

enable_starttls: true requires the connection to upgrade to TLS on port 587 and fails if it cannot. To use port 465 instead, set port: 465 and replace enable_starttls with tls: true, which starts TLS immediately. The SMTP ports guide explains the difference. With Mailcandor’s SMTP relay, the username is always mailcandor and the password is your API key.

domain is the name your app announces in the SMTP greeting; use your own domain.

Option 2: call an email API

You can skip SMTP and post JSON with Net::HTTP from the standard library. This is handy in jobs that build their own content, or in plain Ruby scripts:

require "net/http"
require "json"

def send_email(payload, idempotency_key: nil)
  uri = URI("https://api.mailcandor.com/v1/emails")
  request = Net::HTTP::Post.new(uri)
  request["Authorization"] = "Bearer #{ENV.fetch("MAILCANDOR_KEY")}"
  request["Content-Type"] = "application/json"
  request["Idempotency-Key"] = idempotency_key if idempotency_key
  request.body = payload.to_json

  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 10) do |http|
    http.request(request)
  end

  body = JSON.parse(response.body)
  raise "#{body["error"]["type"]}: #{body["error"]["message"]}" unless response.code == "202"
  body["id"]
end

send_email(
  {
    from: "Acme <hello@acme.com>",
    to: "sam@example.com",
    subject: "Your receipt",
    text: "Thanks for your order."
  },
  idempotency_key: "order-1042-receipt"
)

The idempotency key means that if Active Job retries the job after a timeout, the API returns the first response instead of sending a second receipt. The returned id lets you match webhook events, such as a bounce, to the record that sent it.

To keep your mailer views, you can render a mailer to a Mail::Message and send its parts: message = UserMailer.with(user: user).welcome_email.message, then pass message.html_part.body.decoded and message.text_part.body.decoded as html and text.

Previewing and testing

  • Open /rails/mailers in development to see every preview in test/mailers/previews rendered in the browser.
  • In tests, config.action_mailer.delivery_method = :test collects mail in ActionMailer::Base.deliveries, and assert_enqueued_email_with checks deliver_later calls.
  • In development, the letter_opener gem opens sent mail in your browser instead of delivering it.

Development settings

In config/environments/development.rb, set config.action_mailer.raise_delivery_errors = true while you are working on email, so a broken template or setting fails loudly. Use letter_opener or a local catcher such as Mailpit on port 1025 so test sends never reach real inboxes.

Common errors

  • Net::SMTPAuthenticationError (535): the username or password is wrong, or the credential lookup returned nil. Check with bin/rails runner 'p Rails.application.credentials.dig(:mailcandor, :key).present?'.
  • Net::OpenTimeout or Net::ReadTimeout: the host blocks the port, or the server is slow to answer. Try the other port, or use the API over port 443.
  • OpenSSL::SSL::SSLError with a wrong version number: TLS mode and port do not match. Use enable_starttls with 587 and tls with 465.
  • deliver_later does nothing: no Active Job worker is running in that environment. Check your Solid Queue or Sidekiq process.
  • Links point to localhost: default_url_options is missing or wrong for production.

By default raise_delivery_errors is true, so these errors surface in your job logs. Do not turn it off in production; a silent failure is harder to find than a failed job.

Which should you choose?

Action Mailer (SMTP) Email API (Net::HTTP)
Uses mailer classes and views Yes Render them yourself
Background delivery deliver_later Wrap in an Active Job
Safe retries Not built in Idempotency keys
Delivery events Usually none Webhooks per email id

For most Rails apps, Action Mailer over SMTP is the natural choice: it keeps previews, tests and deliver_later. Use the email API where you need idempotent retries or per-email delivery events.

Before you send: verify your domain

The address in default from: must be on a domain with SPF, DKIM and DMARC records, or receiving servers will filter your mail. Add the domain with your provider and publish the records it gives you; the SPF, DKIM and DMARC guide walks through each one.

Questions

What are the Action Mailer SMTP settings?

address, port, domain, user_name, password, authentication and either enable_starttls (port 587) or tls (port 465), plus optional open_timeout and read_timeout.

What is the difference between deliver_now and deliver_later?

deliver_now sends during the request and waits for the SMTP server. deliver_later enqueues an Active Job so the request returns straight away and a worker sends the email.

Where should I store SMTP credentials in Rails?

In encrypted credentials (bin/rails credentials:edit) or an environment variable, never in the config file itself.

How do I preview emails in Rails?

The mailer generator creates a preview class in test/mailers/previews. In development, open /rails/mailers to see every email rendered in the browser.

How do I send email from plain Ruby without Rails?

Use the mail gem over SMTP, or post JSON to an email API with Net::HTTP from the standard library.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.