How to Send Email from Ruby and Rails with an Email API

Send email from Ruby with an email API for Ruby and Rails, no SMTP server: HTML, attachments, ActiveJob, Action Mailer and replies in the same inbox.

By · · 15 min read

Ruby code from this guide, in send.rb, sending or reading email with Mailcycle

To send email from Ruby with an email API for Ruby, your code makes one HTTPS request with a sender, a recipient, a subject and a body. There is no SMTP server to run, no port 587 versus 465 decision, and no TLS settings to get right. This tutorial shows how to do it with the mailcycle gem: a plain Ruby script first, then Rails, with a controller action, an ActiveJob, and an Action Mailer delivery method so your existing mailers keep working.

You’ll also send HTML email and attachments, thread a reply, and wait for the answer to land in the same inbox. That last part is where Mailcycle differs from a send-only email API: the address you send from is a real mailbox, so replies come back to your Ruby code too.

To read mail as well as send it, see How to receive email in Ruby: create an address, wait for a message, save attachments and handle a Rails webhook. The gem’s own page is Mailcycle for Ruby, and every snippet below was run with version 0.3.1 against a live account.

Quick answer: how do you send email in Ruby?

A Ruby email send with Mailcycle takes three steps. Install the mailcycle gem, build a client from an API key in an environment variable, and call messages.send with a from address on your account, one to recipient, a subject and a text body. The call returns the Message-ID the mail went out with. It works from plain Ruby, Rails, Sidekiq or a Rake task.

gem install mailcycle
require "mailcycle"

mc = Mailcycle.with_api_key(ENV.fetch("MAILCYCLE_API_KEY"))

result = mc.messages.send(
  from: "notifications-x7k2@example-pool.email", # an address on your account
  to: "someone@example.com",
  subject: "Your export is ready",
  text: "Download it from your dashboard."
)
puts result.message_id

That’s the whole thing. The rest of this guide is about doing it well in a real application.

What you’ll build: sending email from Ruby and Rails

By the end you’ll have:

  • a Ruby script that sends a plain-text email, then an HTML email with a PDF and an inline logo;
  • a Rails controller action and an ActiveJob that send transactional mail, with retries that depend on the error code;
  • an Action Mailer delivery method, so UserMailer.welcome(user).deliver_later sends through Mailcycle without touching your views;
  • a reply sent in the same thread as the original, and a script that waits for the next reply to arrive.

Everything here sends from addresses you own, to people who expect your mail: receipts, sign-in links, verification codes, alerts, support replies and agent replies. Each call sends to one recipient, so every message gets your full attention.

Flow: your Ruby code calls the Ruby SDK, Mailcycle sends the email from your address, and the recipient gets it
Your Ruby code calls the Ruby SDK, and Mailcycle sends the email from your address.

Prerequisites for sending email in Ruby

  • Ruby 3.1 or later. Check with ruby -v. The gem’s only dependency is the openssl gem, version 3.0 or later, which Ruby 3.1 already ships.
  • A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key is a Scale feature. The trial needs no card.
  • An API key. API keys start with mak_ and are made in the app.
  • An address on your account to send from. You’ll create one in step 2.
  • Rails 7 or later, only for the Rails sections. The gem itself doesn’t depend on Rails.

Step 1: Create an account and a Ruby email API key

  1. Sign up at app.mailcycle.email/operator/signup. There’s no email or password: the account is a twelve-word recovery phrase made on your device. Save it somewhere safe, because it is the only way back in and it is what opens your mail.
  2. In the sidebar, open Plans & Billing and choose Start free trial, or pick the Scale plan on the pricing page.
  3. Open API, then the Keys tab. Name the key, choose Create key, and copy the token. It is shown once.
  4. Put it in your environment, never in your code:
export MAILCYCLE_API_KEY="mak_..."

In Rails, bin/rails credentials:edit is a good home for it as well; the examples below read ENV to keep them short. The quickstart and authentication docs cover keys in more depth, including what each key is allowed to do.

Step 2: Install the gem and create a sending address

Install it on its own, or add it to your Gemfile:

gem install mailcycle
# or, in a Bundler project
bundle add mailcycle

Every address on a Mailcycle account is a full inbox: it sends, and it receives. Mail is stored encrypted, sealed to a key derived from your recovery phrase, and the gem derives that key on your machine. That’s why creating an address that can receive mail needs the phrase, once:

# create_address.rb, run once
require "mailcycle"

mc = Mailcycle.with_api_key(
  ENV.fetch("MAILCYCLE_API_KEY"),
  phrase: ENV.fetch("MAILCYCLE_PHRASE")
)

address = mc.addresses.create(prefix: "notifications", label: "App mail")
puts address.email_address # notifications-x7k2@...
puts address.id            # ibx_...

prefix: gives you notifications- plus a random ending on a shared domain. On Scale you can also pass local_part: for an exact name, like local_part: "support", or bring your own domain. The phrase never leaves the machine: only the address’s public key goes up, so the mail server can seal what arrives. See Email addresses for styles and rolled names.

Save the address for the examples that follow:

export MAILCYCLE_FROM="notifications-x7k2@example-pool.email"

Step 3: Send your first email from a Ruby script

# send_test.rb
require "mailcycle"

mc = Mailcycle.with_api_key(ENV.fetch("MAILCYCLE_API_KEY"))

result = mc.messages.send(
  from: ENV.fetch("MAILCYCLE_FROM"),
  from_name: "Acme Notifications",
  to: "you@example.com",
  subject: "Hello from Ruby",
  text: "This email was sent from a Ruby script with the Mailcycle API."
)

puts "Sent #{result.message_id}"
puts "Copy in Sent: #{result.sent_copy_id.inspect}"
ruby send_test.rb

A few details worth knowing:

  • from: must be an address on your account. Anything else is refused with not_your_address.
  • to: is one recipient. To mail three people, make three calls, each of which counts towards the plan’s daily sends.
  • from_name: is the display name on the From line. It’s optional, one line, and up to 78 characters.
  • The return value is a Mailcycle::SendResult. message_id is the Message-ID header, worth storing if you’ll match replies later. sent_copy_id is the id of the encrypted copy filed in the address’s Sent folder, or nil when the address keeps none.

Building the client with only an API key makes no network call; the first request happens at send. With phrase: as well, the constructor checks the phrase against the key’s account first, which is one request.

How do I send HTML email in Ruby?

Pass html: alongside text:. The text part is required, and it matters: it is what plain-text mail clients show, and many clients use it for the preview line. A squiggly heredoc keeps the HTML readable:

require "mailcycle"
require "erb"

mc = Mailcycle.with_api_key(ENV.fetch("MAILCYCLE_API_KEY"))

name = "Sam"
link = "https://example.com/verify?token=abc123"

html = <<~HTML
  <!doctype html>
  <html>
    <body style="font-family: system-ui, sans-serif; line-height: 1.5">
      <p>Hi #{ERB::Util.html_escape(name)},</p>
      <p>Confirm your email address to finish signing up:</p>
      <p><a href="#{ERB::Util.html_escape(link)}"
            style="background:#111;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">
        Confirm email</a></p>
      <p>If you didn't sign up, you can ignore this message.</p>
    </body>
  </html>
HTML

text = <<~TEXT
  Hi #{name},

  Confirm your email address to finish signing up:
  #{link}

  If you didn't sign up, you can ignore this message.
TEXT

mc.messages.send(
  from: ENV.fetch("MAILCYCLE_FROM"),
  from_name: "Acme",
  to: "sam@example.com",
  subject: "Confirm your email address",
  text: text,
  html: html
)

Escape anything user-supplied that goes into HTML, as ERB::Util.html_escape does here. Inline styles are still the safest choice for email clients. In Rails you’d render a template instead of a heredoc; that’s in the Rails section below.

How to send email with an attachment in Ruby

Attachments take raw bytes. Read the file with File.binread (not File.read, which can mangle binary data on some platforms) and the gem base64-encodes it for you:

require "mailcycle"

mc = Mailcycle.with_api_key(ENV.fetch("MAILCYCLE_API_KEY"))

files = [
  Mailcycle::OutgoingAttachment.new(
    filename: "invoice-1042.pdf",
    content: File.binread("invoice-1042.pdf"),
    mime_type: "application/pdf"
  ),
  Mailcycle::OutgoingAttachment.new(
    filename: "logo.png",
    content: File.binread("logo.png"),
    mime_type: "image/png",
    content_id: "logo" # shown inline where the HTML says cid:logo
  )
]

mc.messages.send(
  from: ENV.fetch("MAILCYCLE_FROM"),
  to: "billing@customer.example",
  subject: "Invoice 1042",
  text: "Your invoice is attached. Thank you for your order.",
  html: '<p><img src="cid:logo" alt="Acme" width="120"></p><p>Your invoice is attached.</p>',
  attachments: files
)

attachments: also accepts plain hashes with the same keys, which is handy when you’re mapping over records:

attachments = reports.map do |report|
  { filename: report.filename, content: report.bytes, mime_type: "text/csv" }
end

A file with a content_id becomes an inline image for <img src="cid:...">; without one it’s an ordinary attachment. A message carries up to ten files, 3.5 MB between them, and the gem refuses more than that before making a request, with the same error codes the API would use (too_many_attachments, attachments_too_large). Program and script files such as .exe and .js are refused with attachment_blocked, and a file name must be one line with no slashes or quotes (invalid_field), so pass File.basename of a path rather than the path itself. The sending guide has the full rules.

How to send email from Rails with an API

Rails gives you two good places to hook in. You can call the gem directly from a controller or a job, which keeps the result and the error codes in your own code. Or you can register it as an Action Mailer delivery method, so every existing mailer sends through it. Start with one shared client.

One client in an initializer

# config/initializers/mailcycle.rb
require "mailcycle"

# Sending only needs the API key. No network call happens here.
MAILCYCLE = Mailcycle.with_api_key(
  Rails.application.credentials.dig(:mailcycle, :api_key) || ENV.fetch("MAILCYCLE_API_KEY")
)
MAILCYCLE_FROM = ENV.fetch("MAILCYCLE_FROM")

Each request the client makes opens its own HTTPS connection with Ruby’s Net::HTTP, so one client can be shared by every Puma thread and job worker.

A controller action that sends

A contact form is a good example of sending inline: the person is waiting, and you want to tell them if it failed.

# app/controllers/contact_messages_controller.rb
class ContactMessagesController < ApplicationController
  def create
    MAILCYCLE.messages.send(
      from: MAILCYCLE_FROM,
      from_name: "Acme website",
      to: "support@acme.example",
      subject: "Contact form: #{params.require(:subject).to_s.truncate(120)}",
      text: <<~TEXT
        From: #{params.require(:name)} <#{params.require(:email)}>

        #{params.require(:message)}
      TEXT
    )
    redirect_to root_path, notice: "Thanks, we'll be in touch."
  rescue Mailcycle::ApiError => e
    Rails.logger.warn("Contact form send failed: #{e.code} (#{e.status})")
    flash.now[:alert] = "We couldn't send that just now. Please try again in a minute."
    render :new, status: :service_unavailable
  end
end

Log e.code, not the whole message, and never echo the error to the visitor. The code is stable and machine-readable; the message is for people.

An ActiveJob that sends, with retries by error code

Most transactional mail belongs in a background job: the request returns at once, and a temporary failure is retried instead of shown to the user. The interesting part is deciding which failures to retry.

# app/jobs/transactional_email_job.rb
class TransactionalEmailJob < ApplicationJob
  queue_as :mailers

  # Raised for failures that are worth trying again.
  class TemporaryFailure < StandardError; end

  retry_on TemporaryFailure, wait: :polynomially_longer, attempts: 6

  RETRYABLE = %w[
    rate_limited network_error internal send_failed provider_error
    provider_unavailable storage_unavailable maintenance read_only
  ].freeze

  def perform(to:, subject:, text:, html: nil)
    MAILCYCLE.messages.send(
      from: MAILCYCLE_FROM,
      from_name: "Acme",
      to: to,
      subject: subject,
      text: text,
      html: html
    )
  rescue Mailcycle::ApiError => e
    case e.code
    when *RETRYABLE
      raise TemporaryFailure, "#{e.code}: #{e.detail}"
    when "daily_send_limit", "sending_paused"
      # Sending resumes at 00:00 UTC; try again then.
      retry_job(wait_until: Time.now.utc.tomorrow.beginning_of_day)
    else
      # invalid_address, not_your_address, plan_required and the like
      # won't fix themselves. Let it fail where you'll see it.
      raise
    end
  end
end

Enqueue it from anywhere, for example a password reset:

# app/controllers/password_resets_controller.rb
class PasswordResetsController < ApplicationController
  def create
    if (user = User.find_by(email: params.require(:email)))
      token = user.signed_id(purpose: :password_reset, expires_in: 15.minutes)
      link = edit_password_reset_url(token: token)

      TransactionalEmailJob.perform_later(
        to: user.email,
        subject: "Reset your password",
        text: "Reset your password with this link, valid for 15 minutes:\n#{link}",
        html: ApplicationController.render(
          template: "password_resets/email",
          assigns: { link: link },
          layout: false
        )
      )
    end
    # Same answer either way, so the form doesn't reveal who has an account.
    redirect_to root_path, notice: "If that address has an account, a reset link is on its way."
  end
end

Two notes on the retry list. wait: :polynomially_longer is the Rails 7.1+ name; on Rails 7.0 use :exponentially_longer. And network_error means the request never got an answer, so in rare cases the mail did go out; for a password reset a duplicate is better than nothing, but for something like an order confirmation you might prefer to drop it from the list and alert instead.

An Action Mailer alternative that keeps your mailers

If your app already has mailers, previews and ERB templates, you don’t have to rewrite them. Action Mailer lets you plug in any class that responds to deliver!(mail), and the mail object it receives already holds the rendered text, HTML and attachments.

# lib/mailcycle_delivery.rb
class MailcycleDelivery
  attr_accessor :settings

  def initialize(settings)
    @settings = settings
  end

  def deliver!(mail)
    recipients = Array(mail.to) + Array(mail.cc) + Array(mail.bcc)
    unless recipients.one?
      raise ArgumentError, "Mailcycle sends to one recipient per message; got #{recipients.size}"
    end

    html = mail.html_part&.decoded || (mail.mime_type == "text/html" ? mail.body.decoded : nil)
    text = mail.text_part&.decoded || (mail.mime_type == "text/plain" ? mail.body.decoded : nil)
    text ||= ActionController::Base.helpers.strip_tags(html.to_s)

    files = mail.attachments.map do |part|
      {
        filename: part.filename,
        content: part.decoded,
        mime_type: part.mime_type,
        content_id: part.inline? ? part.cid : nil
      }
    end

    settings.fetch(:client).messages.send(
      from: mail.from.first,
      from_name: mail[:from].display_names.first,
      to: recipients.first,
      subject: mail.subject.to_s,
      text: text,
      html: html,
      attachments: files
    )
  end
end

Register it once Action Mailer loads, then switch it on per environment:

# config/initializers/mailcycle.rb (below the client)
require Rails.root.join("lib/mailcycle_delivery").to_s

ActiveSupport.on_load(:action_mailer) do
  add_delivery_method :mailcycle, MailcycleDelivery, client: MAILCYCLE
end
# config/environments/production.rb
config.action_mailer.delivery_method = :mailcycle
config.action_mailer.raise_delivery_errors = true

Now your mailers work unchanged, as long as default from: is an address on your account:

class UserMailer < ApplicationMailer
  default from: "Acme <#{ENV.fetch("MAILCYCLE_FROM")}>"

  def welcome(user)
    @user = user
    attachments.inline["logo.png"] = File.binread(Rails.root.join("app/assets/images/logo.png"))
    mail(to: user.email, subject: "Welcome to Acme")
  end
end

UserMailer.welcome(user).deliver_later

Inline attachments made with attachments.inline[...] keep working, because the delivery method passes each part’s content id through, and image_tag attachments["logo.png"].url in the view produces the matching cid: link. Keep :test as the delivery method in config/environments/test.rb, and your mailer specs and previews stay as they are.

The delivery method raises when a message has more than one recipient instead of quietly picking one. If a mailer sends to a list, send one message per person from a job.

Reply in the same thread and receive email in Ruby

Sending is half of email. The address you send from is an inbox, so when a customer replies to “Invoice 1042”, that reply arrives in your Mailcycle account, encrypted, and your Ruby code can open it. Reading needs the recovery phrase in the client, because the key that opens the mail is derived from it on your machine; the encryption overview explains what is sealed and what isn’t.

Wait for a reply in a script

wait_for returns the next message that matches, already opened. Take the time before you send and pass it as since:, so a fast reply isn’t missed:

require "mailcycle"

mc = Mailcycle.with_api_key(
  ENV.fetch("MAILCYCLE_API_KEY"),
  phrase: ENV.fetch("MAILCYCLE_PHRASE") # needed to open mail
)

address = mc.addresses.list.find { |a| a.email_address == ENV.fetch("MAILCYCLE_FROM") }

since = Time.now
mc.messages.send(
  from: address.email_address,
  to: "ops@example.com",
  subject: "Approve deploy 512?",
  text: "Reply YES to approve the deploy, or NO to cancel it."
)

begin
  reply = mc.messages.wait_for(
    address_id: address.id,
    subject: "Approve deploy 512",
    since: since,
    timeout: 600
  )
rescue Mailcycle::ApiError => e
  raise unless e.code == "timeout"
  abort "No answer in 10 minutes; not deploying."
end

answer = reply.text.lines.first.to_s.strip.upcase
puts "#{reply.from_address} answered: #{answer}"

wait_for listens on the event stream, so it returns the moment the mail arrives, and falls back to checking the address every five seconds where the stream won’t open. subject: and from: match text anywhere in the subject or sender, ignoring case. If nothing arrives in time it raises Mailcycle::ApiError with code "timeout", so a script or spec fails with a reason instead of hanging.

Send a threaded reply

Pass the message you’re answering as reply_to:, and the gem fills in the threading headers (inReplyTo and the original’s Message-ID), so the reply sits under the original in the recipient’s mail client:

mc.messages.send(
  from: address.email_address,
  to: reply.reply_to, # the sender's Reply-To if set, otherwise their From
  subject: "Re: #{reply.subject.delete_prefix("Re: ")}",
  text: "Thanks, deploy 512 is #{answer == "YES" ? "going out now" : "cancelled"}.",
  reply_to: reply
)

Two things share a name here: reply.reply_to is the address a reply should go to, and the reply_to: keyword is the message you’re answering. The reading mail guide covers folders, paging with mc.messages.list, and attachments on received mail, which mc.messages.attachment(message, index) returns as a binary string.

When showing received HTML, use message.safe_html, which has remote images, stylesheets and embeds removed the way the Mailcycle apps do it, rather than message.html.

Receive replies in Rails with a webhook

A web app shouldn’t block a request on wait_for. Add a webhook for message.received in the app (under API, Webhooks), check its signature against the raw body, and hand the message id to a job. Events carry ids, never content, and the endpoint should answer within ten seconds:

# app/controllers/mailcycle_webhooks_controller.rb
class MailcycleWebhooksController < ActionController::API
  def create
    raw = request.raw_post # the body exactly as it arrived
    signature = request.headers["Mailcycle-Signature"]
    secret = Rails.application.credentials.dig(:mailcycle, :webhook_secret)
    return head :unauthorized unless Mailcycle.verify_webhook_signature(secret, raw, signature)

    event = JSON.parse(raw)
    if event["type"] == "message.received"
      HandleReplyJob.perform_later(event.dig("payload", "messageId"), event["id"])
    end
    head :no_content
  end
end
# app/jobs/handle_reply_job.rb
class HandleReplyJob < ApplicationJob
  def perform(message_id, event_id)
    return if ProcessedEvent.exists?(event_id: event_id) # deliveries can repeat
    message = mailcycle_reader.messages.get(message_id)
    SupportTicket.add_reply!(from: message.from_address, subject: message.subject, body: message.text)
    ProcessedEvent.create!(event_id: event_id)
  end

  private

  # Reading needs the phrase; keep it in this process only.
  def mailcycle_reader
    @mailcycle_reader ||= Mailcycle.with_api_key(
      ENV.fetch("MAILCYCLE_API_KEY"),
      phrase: ENV.fetch("MAILCYCLE_PHRASE")
    )
  end
end

ProcessedEvent and SupportTicket stand in for your own models. Deduplicate on the event id because a delivery can arrive more than once.

Ruby email error handling: match on the code

Everything the gem raises is a Mailcycle::Error. A request the API refused, or one that never reached it, is a Mailcycle::ApiError with status (the HTTP status, or 0 when there was no answer), code (stable, like plan_required) and detail (the API’s own message). Match on code:

begin
  mc.messages.send(from: from, to: to, subject: subject, text: text)
rescue Mailcycle::ApiError => e
  case e.code
  when "rate_limited"
    # Too many requests this minute or hour. The message says how long to wait.
    warn "Slow down: #{e.detail}"
  when "daily_send_limit"
    warn "The plan's sends for today are used; sending resumes at 00:00 UTC."
  when "plan_required"
    warn "Sending with an API key needs the Scale plan or above."
  when "not_your_address"
    warn "#{from} isn't an address on this account."
  when "invalid_address"
    warn "#{to.inspect} isn't a valid recipient."
  when "domain_not_sending"
    warn "Sending isn't on yet for that domain; check it under Domains."
  when "attachment_blocked", "too_many_attachments", "attachments_too_large", "message_too_large"
    warn "The attachments were refused: #{e.code}."
  when "network_error", "timeout"
    warn "No answer from the API: #{e.detail}"
  else
    raise
  end
end
Code Status What it means
plan_required 403 The plan doesn’t include this. Sending with an API key starts at Scale.
not_your_address 403 from isn’t an address on this account.
address_paused 403 The address is paused after a missed payment.
invalid_address 400 to isn’t a single valid address.
domain_not_sending 409 Your own domain receives, but sending isn’t on for it yet.
attachments_too_large, message_too_large 413 Over 3.5 MB of files, or 5 MB encoded.
rate_limited 429 Wait and try again.
daily_send_limit 429 The plan’s daily sends are used; resumes at 00:00 UTC.
network_error 0 The request got no answer. Raised by the gem.

The 429 responses carry a Retry-After header. The gem’s error exposes the status, code and message rather than headers, and the message says how long to wait in words, so back off with a delay that grows on each attempt, as the ActiveJob above does. The numbers are in rate limits, and every code is listed in the errors reference. One other class you may meet is Mailcycle::UnsupportedError, raised when you ask a client without the phrase to do something that needs it, such as opening an attachment.

The same send email request with cURL

Under the gem, a send is one JSON POST. Here it is with cURL, useful for checking a key from a shell or for comparing with what your code does:

curl https://api.mailcycle.email/messages/send \
  -H "Authorization: Bearer $MAILCYCLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "notifications-x7k2@example-pool.email",
    "to": "someone@example.com",
    "subject": "Hello",
    "text": "Plain text body",
    "html": "<p>Plain text body</p>"
  }'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }

The gem maps Ruby’s snake_case keywords to the API’s fields (from_name: to fromName, reply_to: to inReplyTo plus inReplyToHeader), base64-encodes attachments, turns error bodies into Mailcycle::ApiError, and never follows redirects, so your key is only ever sent to the API host. The sending guide documents every field. Sending works without the gem; receiving is where it earns its place, because opening encrypted mail means deriving keys from the phrase, which the gem does for you.

Mailcycle gem vs SMTP in Ruby (mail gem, Net::SMTP, Action Mailer)

The classic way to send email in Ruby is SMTP: the mail gem or Net::SMTP directly, or Action Mailer with delivery_method = :smtp. It’s mature and works with any mail server. It also means you need an SMTP server and credentials, and a handful of settings to match:

# config/environments/production.rb, the SMTP way
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address: "smtp.example.com",
  port: 587,
  user_name: ENV["SMTP_USERNAME"],
  password: ENV["SMTP_PASSWORD"],
  authentication: :plain,
  enable_starttls_auto: true
}
SMTP (mail gem, Net::SMTP, Action Mailer :smtp) Mailcycle gem
What you need An SMTP server or relay, plus a username and password An API key and an address on your account
Transport SMTP on port 587 (STARTTLS) or 465 (implicit TLS), which some hosts block HTTPS to api.mailcycle.email
Configuration Host, port, auth method, TLS options Mailcycle.with_api_key(ENV.fetch("MAILCYCLE_API_KEY"))
Dependencies net-smtp is a bundled gem from Ruby 3.1, so it goes in your Gemfile; Rails pulls it in for you mailcycle, which depends only on the openssl gem Ruby ships
Attachments Build MIME parts yourself, or let the mail gem do it Raw bytes in OutgoingAttachment; the gem encodes them
Errors SMTP reply codes and Ruby exceptions such as Net::SMTPAuthenticationError Mailcycle::ApiError with a stable code like daily_send_limit
Replies Need a separate inbox, plus IMAP or Action Mailbox with an ingress such as Postfix or an inbound relay Arrive in the same address; wait_for, webhooks, or the event stream
Stored mail Wherever your mail server keeps it Encrypted with keys derived from your recovery phrase, opened by your Ruby process
Works with Action Mailer Built in As a custom delivery method (above)

An email API for Ruby is simpler when you want sending and receiving from the same Ruby code without operating mail infrastructure. You can also mix the two: keep Action Mailer for templates and previews, and choose the delivery method per environment.

Testing Ruby code that sends email

For unit tests, wrap the client so you can swap it. A tiny double that records calls is enough:

class FakeMessages
  attr_reader :sent

  def initialize
    @sent = []
  end

  def send(**fields)
    @sent << fields
    Mailcycle::SendResult.new(message_id: "<test@example>", sent_copy_id: nil)
  end
end

For end-to-end tests of sign-up and password-reset flows, Mailcycle is useful on the receiving side too: create an address in a before block, fill the form with Capybara, then wait_for the email and read the link from message.text. The Ruby SDK page has a fuller example, and the Ruby SDK guide lists every method.

Security checklist for sending email from Ruby

  • Keep the API key out of code. Use ENV or Rails credentials, never commit it, and never ship it inside software you distribute. Revoke a leaked key in the app under API, Keys; anything using it gets 401 from then on. See API keys.
  • Give the phrase to as few processes as possible. Senders need only the key. Only the code that reads mail or creates addresses needs the phrase, because it opens everything on the account.
  • Verify every webhook with Mailcycle.verify_webhook_signature on the raw body before you parse it.
  • Escape user input in HTML email, as you would in a view.
  • Render safe_html, not html, when you show received mail to anyone.

Next steps for sending email in Ruby

You can now send email from Ruby and Rails with an API, with HTML, attachments and retries, and receive the replies in the same inbox. From here:

FAQ

Is there an email API for Ruby?

Yes. We provide the mailcycle gem, an Apache-2.0 Ruby SDK for the Mailcycle email API. A Ruby email send is one call, mc.messages.send, with HTML, attachments and threaded replies, and the address you send from is a real inbox, so replies come back to the same Ruby code. The Ruby SDK page has the install line and examples.

How do I send an email in Ruby without SMTP?

Install the mailcycle gem, build a client with Mailcycle.with_api_key(ENV.fetch("MAILCYCLE_API_KEY")), and call mc.messages.send(from:, to:, subject:, text:) with an address on your account as from. The gem makes one HTTPS request, so there is no SMTP host, port or TLS setting to configure.

What is the best way to send email from Rails?

Keep Action Mailer for your templates and previews, and choose how it delivers. You can register Mailcycle as a custom delivery method with add_delivery_method, so UserMailer.welcome(user).deliver_later keeps working, or call the gem directly from an ActiveJob when you want the result and error codes in your own code.

How do I send HTML email in Ruby?

Pass html: next to text: in mc.messages.send. The text: part is required and is what plain-text mail clients show, so send both. A heredoc (<<~HTML) or a rendered ERB template works for the HTML.

How do I send an email with an attachment in Ruby?

Pass attachments: an array of Mailcycle::OutgoingAttachment (or plain hashes with the same keys) holding filename, the raw bytes in content, and a mime_type. The gem base64-encodes them for you. Up to ten files and 3.5 MB per message; see Sending mail.

Can I receive email replies in Ruby?

Yes. Every address you send from is a real inbox. mc.messages.wait_for returns the next matching message, and in Rails a webhook tells you when mail arrives. Opening the content needs your recovery phrase in the client, because mail is stored encrypted.

Which Mailcycle plan do I need to send with an API key?

Sending with an API key is on the Scale plan and above. The free 7-day Scale trial includes it with no card. See pricing for what each plan includes.

Why does `mc.messages.send` not behave like Ruby's `send`?

The gem's Messages#send sends email, and it replaces Object#send on that one object. Call it with keywords as shown, and if you need dynamic dispatch on a Messages object, use public_send or __send__, which are unaffected.

Can I send from my own domain in Ruby?

Yes. On Scale you can add up to 10 of your own domains in the app. Once sending is on for a domain, any address on it works as from: with the same code. See Your own domains.

Does the mailcycle gem work in Sidekiq and other background job runners?

Yes. It is a plain Ruby library that depends only on the openssl gem that ships with Ruby, and each request opens its own HTTPS connection with Net::HTTP. Build one client at boot and call it from ActiveJob, Sidekiq, Rake tasks or scripts.

Send email from any language