For the complete site index, see llms.txt. Docs index: llms-docs.txt. Marketing corpus: llms-full.txt. Docs corpus: llms-full-docs.txt. Prefer markdown URLs where available (append .md).. Product skill: skill.md. Pricing: pricing.md. Docs MCP: /docs/mcp.

Tutorials/

How to Send Email in Ruby: Net::SMTP, Rails and API

Pranav Patel

Pranav Patel

Co-founderยท13 min read

How to Send Email in Ruby: Net::SMTP, Rails and API
Summary

Send email from Ruby with Net::SMTP, the mail gem, Rails Action Mailer or Sinatra, or with an email API. Copy-paste examples for HTML email, attachments, background jobs and retries without duplicates.

Ruby can send email with Net::SMTP, and Rails apps already have Action Mailer built in. For anything in production, send through a provider: either over SMTP with Action Mailer or the mail gem, or over HTTPS with an email API SDK.

This guide covers plain Net::SMTP, the mail gem, the Reloop Ruby SDK, Rails and Sinatra, then the production details: attachments, background jobs and safe retries.

Working in another language? See the guides for Python and Node.js.


Which approach should you use?

Net::SMTP / Action Mailer
Email API SDK
Install
net-smtp gem (Rails includes it)
bundle add reloop
Transport
SMTP on port 587 (STARTTLS)
HTTPS on port 443
Building the message
mail gem or mailer views
A hash with html, text, attachments
Errors
Net::SMTPError subclasses
Reloop::Error and Faraday::Error
Safe retries
No, a retry can send twice
Yes, with an idempotency key
Works with Action Mailer and Devise
Yes, natively
Through SMTP settings

If you are wiring up Devise emails, Action Mailer views or a third-party gem, use SMTP settings. If you are writing the send call yourself, use the API.


Prerequisites

  1. Ruby 3.1 or later
  2. A verified sending domain with SPF, DKIM and DMARC
  3. An API key from the Reloop dashboard. Keys start with rl_, and the same key works for the API and SMTP.
bash
export RELOOP_API_KEY=rl_your_api_key

Keep the key in the environment, Rails credentials or a secrets manager, never in your code or git.


Method 1: Send email with Net::SMTP

Net::SMTP speaks the protocol. Since Ruby 3.1 it ships as a bundled gem rather than part of the standard library, so in a Bundler project add it to your Gemfile:

bash
bundle add net-smtp

Then send a plain-text message:

ruby
1require "net/smtp"
2
3message = <<~MESSAGE
4 From: Acme <hello@mail.acme.com>
5 To: user@example.com
6 Subject: Welcome to Acme
7 MIME-Version: 1.0
8 Content-Type: text/plain; charset=UTF-8
9
10 Welcome! Thanks for signing up.
11MESSAGE
12
13Net::SMTP.start(
14 "smtp.reloop.sh", 587,
15 user: "reloop",
16 secret: ENV.fetch("RELOOP_API_KEY"),
17 authtype: :plain,
18 starttls: :always,
19) do |smtp|
20 smtp.send_message(message, "hello@mail.acme.com", "user@example.com")
21end

The username can be any string. The password is your API key. starttls: :always makes the connection fail instead of falling back to plain text if TLS is not available.

Build HTML email with the mail gem

Writing MIME by hand gets messy once you need HTML, a plain-text fallback or attachments. The mail gem (the same one Action Mailer uses) builds the message and sends it over SMTP:

bash
bundle add mail
ruby
1require "mail"
2
3Mail.defaults do
4 delivery_method :smtp,
5 address: "smtp.reloop.sh",
6 port: 587,
7 user_name: "reloop",
8 password: ENV.fetch("RELOOP_API_KEY"),
9 authentication: :plain,
10 enable_starttls: true
11end
12
13mail = Mail.new do
14 from "Acme <hello@mail.acme.com>"
15 to "user@example.com"
16 subject "Welcome to Acme"
17
18 # Plain-text body first, then the HTML alternative
19 text_part do
20 body "Welcome! Thanks for signing up."
21 end
22
23 html_part do
24 content_type "text/html; charset=UTF-8"
25 body "<h1>Welcome!</h1><p>Thanks for signing up.</p>"
26 end
27end
28
29mail.deliver!

When port 587 is blocked

Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port number changes:

ruby
1Net::SMTP.start(
2 "smtp.reloop.sh", 2587,
3 user: "reloop",
4 secret: ENV.fetch("RELOOP_API_KEY"),
5 authtype: :plain,
6 starttls: :always,
7) do |smtp|
8 smtp.send_message(message, "hello@mail.acme.com", "user@example.com")
9end

Reloop does not offer implicit TLS on port 465, so do not pass tls: true to Net::SMTP, or ssl: true / tls: true to the mail gem or Action Mailer. If the connection hangs or times out, see SMTP ports explained.

Handle SMTP errors

ruby
1begin
2 Net::SMTP.start(
3 "smtp.reloop.sh", 587,
4 user: "reloop",
5 secret: ENV.fetch("RELOOP_API_KEY"),
6 authtype: :plain,
7 starttls: :always,
8 ) do |smtp|
9 smtp.send_message(message, "hello@mail.acme.com", "user@example.com")
10 end
11rescue Net::SMTPAuthenticationError
12 warn "Wrong API key"
13rescue Net::SMTPServerBusy => e
14 warn "Temporary failure, try again later: #{e.message}"
15rescue Net::SMTPFatalError, Net::SMTPSyntaxError => e
16 warn "Rejected: #{e.message}"
17rescue Net::OpenTimeout, Net::ReadTimeout, SystemCallError => e
18 warn "Network error: #{e.message}"
19end

SMTP codes run the other way from HTTP: 4xx replies (Net::SMTPServerBusy) are temporary and worth retrying, 5xx replies (Net::SMTPFatalError) are permanent.

Can I send with Gmail from Ruby?

For a personal script, yes: use smtp.gmail.com on port 587 with an App Password. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.


Method 2: Send email with the Ruby SDK

Install

bash
bundle add reloop

Or gem install reloop outside Bundler. The gem is reloop and you load it with require "reloop".

Send an email

ruby
1require "reloop"
2
3reloop = Reloop::Client.new(api_key: ENV.fetch("RELOOP_API_KEY"))
4
5begin
6 result = reloop.mail.send(
7 from: "Acme <hello@mail.acme.com>",
8 to: "user@example.com",
9 subject: "Welcome to Acme",
10 html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
11 text: "Welcome! Thanks for signing up.",
12 )
13 puts "Sent: #{result["id"]}"
14rescue Reloop::Error => e
15 warn "Failed: #{e.message}"
16rescue Faraday::Error => e
17 warn "Network error: #{e.message}"
18end

The SDK raises on failure. When the API answers with a non-2xx status you get a Reloop::Error whose message includes the status code and the error body. Connection failures and timeouts surface as Faraday::Error, since the SDK uses Faraday for HTTP. On success, send returns the parsed JSON response as a hash with string keys, so read the email ID with result["id"].

The SDK passes your hash to the API as JSON, so field names match the API reference exactly: reply_to, scheduled_at, template, attachments.

Send to several recipients

ruby
1reloop.mail.send(
2 from: "Acme <hello@mail.acme.com>",
3 to: ["ada@example.com", "grace@example.com"],
4 cc: "team@acme.com",
5 reply_to: "support@acme.com",
6 subject: "Your weekly report",
7 text: "Here is your report.",
8 tags: [{ name: "type", value: "weekly_report" }],
9)

Every address in to sees the others. For personalized mail, send one message per recipient.

Send a stored template

Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:

ruby
1reloop.mail.send(
2 from: "Acme <hello@mail.acme.com>",
3 to: "user@example.com",
4 subject: "Welcome to Acme",
5 template: {
6 id: "tmpl_welcome",
7 variables: { first_name: "Ada", plan: "Pro" },
8 },
9)

See templates for variables and defaults.


Rails

Action Mailer works with any SMTP provider. Point it at Reloop and your mailers, Devise emails and password reset emails all go through Reloop.

Store the key in credentials

bash
bin/rails credentials:edit
yaml
reloop:
api_key: rl_your_api_key

Configure Action Mailer

config/environments/production.rb
1Rails.application.configure do
2 config.action_mailer.delivery_method = :smtp
3 config.action_mailer.smtp_settings = {
4 address: "smtp.reloop.sh",
5 port: 587,
6 user_name: "reloop",
7 password: Rails.application.credentials.dig(:reloop, :api_key),
8 authentication: :plain,
9 enable_starttls: true,
10 }
11 config.action_mailer.default_url_options = { host: "acme.com", protocol: "https" }
12 config.action_mailer.raise_delivery_errors = true
13end

Leave ssl and tls unset: Reloop uses STARTTLS, not implicit TLS. If 587 is blocked, set port: 2587.

Write a mailer

app/mailers/application_mailer.rb
1class ApplicationMailer < ActionMailer::Base
2 default from: "Acme <hello@mail.acme.com>"
3 layout "mailer"
4end
5
6# app/mailers/user_mailer.rb
7class UserMailer < ApplicationMailer
8 def welcome
9 @user = params[:user]
10 mail(to: @user.email, subject: "Welcome to Acme")
11 end
12end

Add both app/views/user_mailer/welcome.html.erb and app/views/user_mailer/welcome.text.erb. Action Mailer sees the two templates and sends a multipart email with HTML and a plain-text fallback.

Send it with deliver_later

ruby
UserMailer.with(user: @user).welcome.deliver_later

deliver_later hands the email to Active Job, so the request returns without waiting on SMTP. New Rails 8 apps use Solid Queue in production, which stores jobs in your database so they survive restarts. Use deliver_now only in scripts and consoles.

Use the SDK from Rails

When you want the API instead of SMTP, create one client in an initializer and reuse it:

config/initializers/reloop.rb
1RELOOP = Reloop::Client.new(
2 api_key: Rails.application.credentials.dig(:reloop, :api_key),
3)
app/controllers/contacts_controller.rb
1class ContactsController < ApplicationController
2 def create
3 result = RELOOP.mail.send(
4 from: "Acme Website <contact@mail.acme.com>",
5 to: "support@acme.com",
6 reply_to: params.require(:email),
7 subject: "New message from #{params[:email]}",
8 text: params.require(:message),
9 )
10 render json: { id: result["id"] }
11 rescue Reloop::Error, Faraday::Error
12 render json: { error: "Could not send message" }, status: :bad_gateway
13 end
14end

The visitor's address goes in reply_to, never in from. You can only send from your verified domain, and putting someone else's domain in from fails DMARC. Full example: Rails guide.


Sinatra

app.rb
1require "sinatra"
2require "json"
3require "reloop"
4
5RELOOP = Reloop::Client.new(api_key: ENV.fetch("RELOOP_API_KEY"))
6
7post "/contact" do
8 content_type :json
9 data = JSON.parse(request.body.read)
10
11 result = RELOOP.mail.send(
12 from: "Acme Website <contact@mail.acme.com>",
13 to: "support@acme.com",
14 reply_to: data["email"],
15 subject: "New contact form message",
16 text: data["message"],
17 )
18 { id: result["id"] }.to_json
19rescue Reloop::Error, Faraday::Error
20 halt 502, { error: "Could not send message" }.to_json
21end

Prefer SMTP? Use the mail gem settings from Method 1 with the same host, port and credentials.


Attachments

With the SDK, pass base64 content:

ruby
1require "base64"
2
3pdf = File.binread("invoice-1042.pdf")
4
5reloop.mail.send(
6 from: "Acme Billing <billing@mail.acme.com>",
7 to: "user@example.com",
8 subject: "Your invoice #1042",
9 text: "Your invoice is attached.",
10 attachments: [{
11 filename: "invoice-1042.pdf",
12 content: Base64.strict_encode64(pdf),
13 content_type: "application/pdf",
14 }],
15)

On Ruby 3.4 and later, base64 is a bundled gem too. Rails already depends on it; in a plain Bundler project, run bundle add base64.

In a Rails mailer, assign to attachments:

ruby
1def invoice
2 attachments["invoice-1042.pdf"] = File.binread(Rails.root.join("tmp/invoice-1042.pdf"))
3 mail(to: params[:user].email, subject: "Your invoice #1042")
4end

With the mail gem, use add_file:

ruby
mail.add_file(filename: "invoice-1042.pdf", content: pdf)

Keep attachments small. Many inboxes reject messages over 25 MB, and large files hurt deliverability. For big files, send a signed download link.


Send in the background with Active Job

Sending inside a web request adds latency and fails the request when the provider is slow. deliver_later already moves Action Mailer sends into a job. Active Job does not retry failed deliveries on its own (some backends, like Sidekiq, add their own retries), so tell the delivery job which errors are temporary:

app/jobs/retrying_mail_delivery_job.rb
1class RetryingMailDeliveryJob < ActionMailer::MailDeliveryJob
2 retry_on Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNRESET,
3 Errno::ECONNREFUSED, Net::SMTPServerBusy,
4 wait: :polynomially_longer, attempts: 5
5end
6
7# app/mailers/application_mailer.rb
8class ApplicationMailer < ActionMailer::Base
9 self.delivery_job = RetryingMailDeliveryJob
10 default from: "Acme <hello@mail.acme.com>"
11 layout "mailer"
12end

wait: :polynomially_longer needs Rails 7.1 or later. Net::SMTPFatalError and Net::SMTPAuthenticationError are left out on purpose. An invalid address or a wrong key fails the same way every time.

For API sends, write the job yourself. The rules are the same as for any HTTP API: retry network errors (no status at all), 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time. The next section shows that job, with an idempotency key so retries are safe.


Retries without duplicate emails

A request times out and your job retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original send instead of sending again.

Reloop::Error does not expose the status code as a field, so this job calls the endpoint with Net::HTTP to decide what to retry:

app/jobs/send_receipt_job.rb
1require "net/http"
2require "json"
3
4class SendReceiptJob < ApplicationJob
5 class RetryableSendError < StandardError; end
6
7 SEND_URL = URI("https://reloop.sh/api/mail/v1/send")
8
9 retry_on RetryableSendError, wait: :polynomially_longer, attempts: 5
10
11 def perform(order_id, to)
12 request = Net::HTTP::Post.new(SEND_URL)
13 request["x-api-key"] = Rails.application.credentials.dig(:reloop, :api_key)
14 request["Content-Type"] = "application/json"
15 request["Idempotency-Key"] = "receipt-#{order_id}"
16 request.body = {
17 from: "Acme <orders@mail.acme.com>",
18 to: to,
19 subject: "Receipt for order #{order_id}",
20 text: "Thanks for your order.",
21 }.to_json
22
23 response = Net::HTTP.start(
24 SEND_URL.host, SEND_URL.port,
25 use_ssl: true, open_timeout: 10, read_timeout: 30,
26 ) { |http| http.request(request) }
27
28 status = response.code.to_i
29 return JSON.parse(response.body)["id"] if response.is_a?(Net::HTTPSuccess)
30
31 if status == 429 || status >= 500
32 raise RetryableSendError, "Reloop returned #{status}"
33 end
34
35 # Other 4xx: do not retry
36 raise "Send failed (#{status}): #{response.body}"
37 rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError => e
38 raise RetryableSendError, e.message
39 end
40end
ruby
SendReceiptJob.perform_later(order.id, order.email)

Base the key on the business event (receipt-#{order_id}), not a new UUID per attempt, so retries from any worker are safe. If an attempt failed before the email went out, a retry with the same key sends it.

If you only need deduplication and not status-based retries, the SDK works too. The API also reads the key from an idempotency_key field in the body, and the SDK passes it through:

ruby
1reloop.mail.send(
2 from: "Acme <orders@mail.acme.com>",
3 to: order.email,
4 subject: "Receipt for order #{order.id}",
5 text: "Thanks for your order.",
6 idempotency_key: "receipt-#{order.id}",
7)

Testing without sending real email

  • Rails: the test environment uses the :test delivery method, which stores emails in ActionMailer::Base.deliveries instead of sending them. Call deliver_now in mailer tests, or wrap deliver_later in perform_enqueued_jobs, then assert on the array.
  • Anything else: stub the client in unit tests, and send to test addresses in staging so you do not hurt your sender reputation with bounces.
  • Local SMTP: run Mailpit with docker run -p 1025:1025 -p 8025:8025 axllent/mailpit. In config/environments/development.rb, set config.action_mailer.delivery_method = :smtp and config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }, with no user name, password or enable_starttls. Open http://localhost:8025 to see the messages.
test/mailers/user_mailer_test.rb
1class UserMailerTest < ActionMailer::TestCase
2 test "welcome" do
3 user = users(:ada)
4 UserMailer.with(user: user).welcome.deliver_now
5
6 email = ActionMailer::Base.deliveries.last
7 assert_equal [user.email], email.to
8 assert_equal "Welcome to Acme", email.subject
9 end
10end

Production checklist

  • API key in Rails credentials, an environment variable or a secrets manager
  • Sending domain verified with SPF, DKIM and DMARC
  • from on your verified domain; user addresses in reply_to
  • Both HTML and plain-text bodies (.html.erb and .text.erb views)
  • One shared client, created in an initializer
  • Sending in a job (deliver_later, Solid Queue, Sidekiq), not the request
  • Retries only on network errors, 429 and 5xx (or SMTP 4xx)
  • Idempotency keys on anything that retries
  • Webhooks for bounces and complaints
  • Disposable addresses blocked at signup (how)

FAQ

With the mail gem, add a text_part with the plain-text version and an html_part with your HTML and a text/html content type. In Rails, add both an .html.erb and a .text.erb view for the mailer action. With the Reloop SDK, pass html and text keys to mail.send.

Since Ruby 3.1, net-smtp is a bundled gem, not part of the default standard library. Under Bundler you have to list it in your Gemfile with bundle add net-smtp. Rails apps get it through the mail gem.

Use 587 with enable_starttls set to true. Port 465 expects implicit TLS, which needs ssl or tls set to true instead. Reloop only offers STARTTLS, on ports 587, 2587 and 2025, so leave ssl and tls unset.

Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.

Yes. Devise sends through Action Mailer, so the SMTP settings shown above route confirmation, password reset and unlock emails through Reloop with no code changes.


W: 320.0px180R20โˆ 45.0ยฐ

Ship your first email with Reloop
in minutes.

Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.

Reloop