How to Send Email in Ruby: Net::SMTP, Rails and API
Pranav Patel
Co-founderยท13 min read
On this page

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 Mailernet-smtp gem (Rails includes it)bundle add reloopmail gem or mailer viewshtml, text, attachmentsNet::SMTPError subclassesReloop::Error and Faraday::ErrorIf 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
- Ruby 3.1 or later
- A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep 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:
bundle add net-smtpThen send a plain-text message:
1require "net/smtp"2
3message = <<~MESSAGE4 From: Acme <hello@mail.acme.com>5 To: user@example.com6 Subject: Welcome to Acme7 MIME-Version: 1.08 Content-Type: text/plain; charset=UTF-89
10 Welcome! Thanks for signing up.11MESSAGE12
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")21endThe 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:
bundle add mail1require "mail"2
3Mail.defaults do4 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: true11end12
13mail = Mail.new do14 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 alternative19 text_part do20 body "Welcome! Thanks for signing up."21 end22
23 html_part do24 content_type "text/html; charset=UTF-8"25 body "<h1>Welcome!</h1><p>Thanks for signing up.</p>"26 end27end28
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:
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")9endReloop 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
1begin2 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 end11rescue Net::SMTPAuthenticationError12 warn "Wrong API key"13rescue Net::SMTPServerBusy => e14 warn "Temporary failure, try again later: #{e.message}"15rescue Net::SMTPFatalError, Net::SMTPSyntaxError => e16 warn "Rejected: #{e.message}"17rescue Net::OpenTimeout, Net::ReadTimeout, SystemCallError => e18 warn "Network error: #{e.message}"19endSMTP 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
bundle add reloopOr gem install reloop outside Bundler. The gem is reloop and you load it with require "reloop".
Send an email
1require "reloop"2
3reloop = Reloop::Client.new(api_key: ENV.fetch("RELOOP_API_KEY"))4
5begin6 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 => e15 warn "Failed: #{e.message}"16rescue Faraday::Error => e17 warn "Network error: #{e.message}"18endThe 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
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:
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
bin/rails credentials:editreloop: api_key: rl_your_api_keyConfigure Action Mailer
1Rails.application.configure do2 config.action_mailer.delivery_method = :smtp3 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 = true13endLeave ssl and tls unset: Reloop uses STARTTLS, not implicit TLS. If 587 is blocked, set port: 2587.
Write a mailer
1class ApplicationMailer < ActionMailer::Base2 default from: "Acme <hello@mail.acme.com>"3 layout "mailer"4end5
6# app/mailers/user_mailer.rb7class UserMailer < ApplicationMailer8 def welcome9 @user = params[:user]10 mail(to: @user.email, subject: "Welcome to Acme")11 end12endAdd 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
UserMailer.with(user: @user).welcome.deliver_laterdeliver_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:
1RELOOP = Reloop::Client.new(2 api_key: Rails.application.credentials.dig(:reloop, :api_key),3)1class ContactsController < ApplicationController2 def create3 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::Error12 render json: { error: "Could not send message" }, status: :bad_gateway13 end14endThe 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
1require "sinatra"2require "json"3require "reloop"4
5RELOOP = Reloop::Client.new(api_key: ENV.fetch("RELOOP_API_KEY"))6
7post "/contact" do8 content_type :json9 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_json19rescue Reloop::Error, Faraday::Error20 halt 502, { error: "Could not send message" }.to_json21endPrefer SMTP? Use the mail gem settings from Method 1 with the same host, port and credentials.
Attachments
With the SDK, pass base64 content:
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:
1def invoice2 attachments["invoice-1042.pdf"] = File.binread(Rails.root.join("tmp/invoice-1042.pdf"))3 mail(to: params[:user].email, subject: "Your invoice #1042")4endWith the mail gem, use add_file:
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:
1class RetryingMailDeliveryJob < ActionMailer::MailDeliveryJob2 retry_on Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNRESET,3 Errno::ECONNREFUSED, Net::SMTPServerBusy,4 wait: :polynomially_longer, attempts: 55end6
7# app/mailers/application_mailer.rb8class ApplicationMailer < ActionMailer::Base9 self.delivery_job = RetryingMailDeliveryJob10 default from: "Acme <hello@mail.acme.com>"11 layout "mailer"12endwait: :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:
1require "net/http"2require "json"3
4class SendReceiptJob < ApplicationJob5 class RetryableSendError < StandardError; end6
7 SEND_URL = URI("https://reloop.sh/api/mail/v1/send")8
9 retry_on RetryableSendError, wait: :polynomially_longer, attempts: 510
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_json22
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_i29 return JSON.parse(response.body)["id"] if response.is_a?(Net::HTTPSuccess)30
31 if status == 429 || status >= 50032 raise RetryableSendError, "Reloop returned #{status}"33 end34
35 # Other 4xx: do not retry36 raise "Send failed (#{status}): #{response.body}"37 rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError => e38 raise RetryableSendError, e.message39 end40endSendReceiptJob.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:
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
:testdelivery method, which stores emails inActionMailer::Base.deliveriesinstead of sending them. Calldeliver_nowin mailer tests, or wrapdeliver_laterinperform_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. Inconfig/environments/development.rb, setconfig.action_mailer.delivery_method = :smtpandconfig.action_mailer.smtp_settings = { address: "localhost", port: 1025 }, with no user name, password orenable_starttls. Openhttp://localhost:8025to see the messages.
1class UserMailerTest < ActionMailer::TestCase2 test "welcome" do3 user = users(:ada)4 UserMailer.with(user: user).welcome.deliver_now5
6 email = ActionMailer::Base.deliveries.last7 assert_equal [user.email], email.to8 assert_equal "Welcome to Acme", email.subject9 end10endProduction checklist
- API key in Rails credentials, an environment variable or a secrets manager
- Sending domain verified with SPF, DKIM and DMARC
-
fromon your verified domain; user addresses inreply_to - Both HTML and plain-text bodies (
.html.erband.text.erbviews) - One shared client, created in an initializer
- Sending in a job (
deliver_later, Solid Queue, Sidekiq), not the request - Retries only on network errors,
429and5xx(or SMTP4xx) - 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.
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.


