Receive Email in Ruby and Rails: Read the Inbox, Save Attachments and Handle Webhooks

Receive email in Ruby with an email API: create an address, read the inbox, save attachments and get new mail in a Rails or Sinatra webhook.

By · · 12 min read

Ruby code that reads the newest message in a Mailcycle inbox with the Ruby SDK

Receive email in Ruby with a few lines of code: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in a test, or hand a customer’s reply to your Rails app. Ruby’s standard library reads mail with Net::IMAP, which means a mailbox and its password, and Rails adds Action Mailbox on top, which means an ingress to set up. If what you want is “give my program an address and let it read what arrives”, an email API for Ruby is shorter.

This tutorial shows how to receive and read email in Ruby with Mailcycle’s Ruby SDK, the mailcycle gem, version 0.3.1. Every method used here is documented in the Ruby SDK guide, and every snippet was run against a live account with that version. You’ll create an address, list and open messages, save attachments to disk, wait for the next email, and then get new mail pushed to a Rails controller or a Sinatra route by webhook.

It is the receiving half of How to send email from Ruby and Rails, the guide to the Ruby email send side: HTML, attachments you send, Action Mailer and threaded replies. This one goes deep on the inbox.

Quick answer: how to receive email in Ruby

Install the gem, sign in with your recovery phrase, create an address, and call wait_for. It returns when a message arrives, parsed and decrypted, with the sender, subject, text, HTML and attachments as plain attributes.

gem install mailcycle
require "mailcycle"

mc = Mailcycle.sign_in(ENV.fetch("MAILCYCLE_PHRASE"))

address = mc.addresses.create(prefix: "inbound", label: "Ruby inbox")
puts "Send an email to #{address.email_address}"

message = mc.messages.wait_for(address_id: address.id, timeout: 300)
puts "#{message.from_address} #{message.subject}"
puts message.text

Run it, send an email to the address it prints from any mail app, and the script prints what you sent. The rest of this guide is what a real app needs around that: paging, attachments, push and errors.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, the Ruby SDK lists, waits for or receives it by webhook, and your Ruby code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your Ruby code reads it with the Ruby SDK, by waiting for it or from a webhook.

Prerequisites

  • Ruby 3.1 or later. Check with ruby -v. The gem needs only gems that ship with Ruby.
  • A Mailcycle account. Receiving works on every plan when your program signs in with the recovery phrase. API keys and webhooks start at Operator. Pricing has the plans.
  • Your recovery phrase, in an environment variable named MAILCYCLE_PHRASE, for any process that opens mail. The next section shows where it comes from.

Get a recovery phrase for your Ruby code

There is no sign-up form and no API key to start with: the account is its twelve-word recovery phrase. Make a free account at app.mailcycle.email/operator/signup and keep the twelve words it shows, or make one from Ruby once the gem is installed:

require "mailcycle"

mc, phrase = Mailcycle.create_account
File.write("mailcycle-phrase.txt", phrase, perm: 0o600) # the only copy: keep it safe
puts mc.account_id

Then hand it to every script in this guide through the environment:

export MAILCYCLE_PHRASE="$(cat mailcycle-phrase.txt)"

The gem accepts the words in any case and ignores a trailing newline, so a phrase read from a file works as it is. A word that is not on the list is named in the error (Word 10 is not in the list), which makes a typo quick to find. The Your recovery phrase section of the guide has the same steps.

Step 1: Install the gem

gem install mailcycle

In a project, add gem "mailcycle" to your Gemfile and run bundle install. The gem has three handles you use for mail: mc.addresses, mc.messages and mc.webhooks.

Step 2: Sign in and create an address

Mailcycle.sign_in(phrase) works on every plan. Each sign-in opens a 30-day session, so a program that runs often can keep mc.session_token and pick it up again with Mailcycle.resume(token, phrase).

An address that receives mail needs a public key the mail server can encrypt to. addresses.create derives that key from your phrase and uploads only the public half.

address = mc.addresses.create(
  prefix: "invoices",
  label: "Supplier invoices",
  retention_days: 30
)
puts "#{address.email_address} #{address.id}"

mc.addresses.list.each do |existing|
  puts "#{existing.email_address} #{existing.label} #{existing.receives}"
end

The keywords on create:

  • prefix: "invoices" gives invoices- plus a random ending on a shared domain.
  • style: (:person, :business, :team or :neutral) rolls a name in that style.
  • local_part: asks for an exact name. Any name you type needs Scale or above, and so does domain: with your own domain.
  • label: is encrypted on your machine, so the server stores it as ciphertext.
  • retention_days: is 1 to 90, and 7 when left out.

Save address.id, the ibx_... id: every reading call takes it.

Step 3: List and read emails in the inbox

messages.list returns one page of a folder, newest first:

page = mc.messages.list(address.id, limit: 20)
page.messages.each do |message|
  flag = message.read ? " " : "*"
  puts "#{flag} #{message.received_at} #{message.from_address} #{message.subject}"
end

if page.next_cursor
  older = mc.messages.list(address.id, limit: 20, cursor: page.next_cursor)
  puts "#{older.messages.size} older messages on the next page"
end

next_cursor is opaque: pass it back as cursor: as it came, and it is nil on the last page. To walk a whole folder, all pages for you:

all = mc.messages.all(address.id)

invoices = all.select do |message|
  message.subject.downcase.include?("invoice") && !message.attachments.empty?
end
puts "#{invoices.size} invoices with files attached"

Message content is encrypted, so you decrypt and then filter in Ruby, as above. Pass folder: "sent", "junk", "trash" or "starred" to read another one.

What is in a Message

Each message is a plain Struct, already parsed from MIME and decrypted:

Attribute What it holds
id, address_id The message’s msg_... id and the address it arrived at.
received_at When it arrived, as an RFC 3339 string in UTC.
from_address, from_name The sender’s address and display name.
reply_to Where a reply should go: the Reply-To header if set, otherwise From.
to, subject The recipient and the subject line.
text The plain-text body.
html The HTML body exactly as sent. Do not render this one.
safe_html The HTML with remote images, trackers and embeds removed.
attachments An array of Mailcycle::Attachment: index, filename, mime_type, size, content_id, stored.
message_id The sender’s Message-ID header, used to thread a reply.
read, starred, folder The message’s state.
opened false if it could not be decrypted: no phrase, or the wrong one.

A message that does not open comes back with opened set to false and empty content rather than an error, so one bad message never hides the rest of a page.

Read the email body in Ruby: text, html and safe_html

Most mail carries a plain-text and an HTML part. Use text for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, use safe_html:

message = mc.messages.get("msg_91be02c4a7d1")
abort "this message did not open: check the recovery phrase" unless message.opened

puts message.text.empty? ? "(no plain-text part)" : message.text

unless message.safe_html.empty?
  File.write("preview.html", message.safe_html)
  puts "#{message.blocked.size} remote items taken out"
end

get fetches one message by id, from any folder. safe_html is the HTML the Mailcycle apps show: remote images, tracking pixels and embeds are taken out, so opening it does not tell the sender when you read it. In a Rails view, render it inside a sandboxed <iframe> rather than straight into the page.

Download email attachments in Ruby

Attachments are listed on the message and fetched one at a time. Their bodies are encrypted like the message, and attachment opens them on your machine. This method saves a message’s files safely:

require "fileutils"

def save_attachments(mc, message, folder)
  target = File.join(folder, message.id)
  message.attachments.filter_map do |attachment|
    next unless attachment.stored     # an empty part: nothing to fetch
    next if attachment.content_id     # an image the HTML shows inline, like a logo

    data = mc.messages.attachment(message, attachment.index) # opened on this machine
    FileUtils.mkdir_p(target)
    name = File.basename(attachment.filename.tr("\\", "/"))
    name = "attachment" if name.empty? || name == "." || name == ".."
    path = File.join(target, "#{attachment.index}-#{name}")
    File.binwrite(path, data)
    path
  end
end

Then process every unread message that has files, and mark each one read so the next run skips it:

mc.messages.all(address.id).each do |message|
  next if message.read || message.attachments.empty?

  save_attachments(mc, message, "downloads").each { |path| puts "saved #{path}" }
  mc.messages.mark_read(message.id, true)
end

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../.bashrc is a classic path-traversal trick. File.basename keeps the last path component, and the index prefix keeps two files called invoice.pdf apart.
  • stored is false for a part that had no body. Skip it.
  • content_id is set on an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the logo.
  • mime_type and size let you keep only application/pdf, or refuse anything over a size, before you download it.
  • Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.

That is the job a Ruby email parser does for attachments, without walking a MIME tree or decoding base64.

Wait for the next email in Ruby

wait_for returns when a matching message arrives, opened. It is the shortest way to read a verification email in an end-to-end test, or to wait for a reply:

started = Time.now # take the time before the email is triggered

# ...trigger the email here: submit a sign-up form, call your own API...

begin
  message = mc.messages.wait_for(
    address_id: address.id,
    subject: "verify",
    since: started,
    timeout: 120
  )
rescue Mailcycle::ApiError => e
  abort "no verification email within two minutes" if e.code == "timeout"
  raise
end

code = message.text[/\b\d{6}\b/]
abort "no code in: #{message.text.inspect}" unless code
puts "code: #{code}"

How it behaves:

  • since: is the important one. Mail received from that moment on counts, even if it landed before the wait began. Take the time before you trigger the email, so a fast delivery cannot slip past. It defaults to when wait_for is called.
  • from: and subject: match text the sender or subject contains, ignoring case. address_id: limits the wait to one address.
  • timeout: is 60 seconds by default. When it runs out you get a Mailcycle::ApiError with code set to "timeout".
  • poll_every: (five seconds by default) is how often it checks when the live stream is not available.

In an RSpec test, create the address before the example and delete it after:

RSpec.describe "sign-up email" do
  let(:mc) { Mailcycle.sign_in(ENV.fetch("MAILCYCLE_PHRASE")) }
  let!(:address) { mc.addresses.create(prefix: "test", retention_days: 1) }

  after { mc.addresses.delete(address.id) }

  it "sends a six-digit code" do
    started = Time.now
    sign_up(email: address.email_address)

    message = mc.messages.wait_for(address_id: address.id, subject: "verify", since: started)
    expect(message.text).to match(/\b\d{6}\b/)
  end
end

Mark as read, star, move and delete

These calls change state only, so they do not open any content:

Call What it does
mc.messages.mark_read(id, true) Marks read. mark_read(id, false) marks unread.
mc.messages.star(id, true) Stars it. star(id, false) unstars.
mc.messages.move_to(id, "junk") Moves to "inbox", "junk" or "trash".
mc.messages.delete(id) Deletes it now.

Get new email pushed to Rails with a webhook

Mailcycle can tell your app the moment mail arrives. A message.received event carries the message’s id and its address’s id. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.

Add a webhook in the app under API, on the Webhooks tab, or from Ruby with a signed-in session:

created = mc.webhooks.create(
  "https://example.com/hooks/mailcycle",
  ["message.received"],
  "Inbound mail"
)
puts "#{created.webhook.id} #{created.secret}" # whsec_..., shown once: store it as MAILCYCLE_WEBHOOK_SECRET

The URL must be HTTPS. To try a webhook on your laptop, run bin/rails server and expose it through an https tunnel such as Cloudflare Tunnel or ngrok, then register the tunnel’s URL; an http://localhost URL is refused with invalid_url, and the error links to Test on your own machine. Once it is registered, mc.webhooks.test(created.webhook.id) queues a signed test delivery, so you can check the handler before any real mail arrives.

First, a shared client for the app, kept in one place:

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

module MailcycleClient
  def self.get
    @get ||= Mailcycle.sign_in(ENV.fetch("MAILCYCLE_PHRASE"))
  end
end

Then the route, the controller and a job:

# config/routes.rb
post "/hooks/mailcycle", to: "mailcycle_webhooks#create"
# app/controllers/mailcycle_webhooks_controller.rb
class MailcycleWebhooksController < ApplicationController
  skip_forgery_protection

  def create
    raw = request.raw_post # the exact body, before any parsing

    unless Mailcycle.verify_webhook_signature(
      ENV.fetch("MAILCYCLE_WEBHOOK_SECRET"), raw, request.headers["Mailcycle-Signature"]
    )
      return head :unauthorized
    end

    event_id = request.headers["Mailcycle-Event-Id"]
    if event_id && !Rails.cache.write("mailcycle-event:#{event_id}", true, unless_exist: true, expires_in: 1.day)
      return head :no_content # a retry of an event already handled
    end

    event = JSON.parse(raw)
    if event["type"] == "message.received"
      ProcessInboundMailJob.perform_later(event.dig("payload", "messageId"))
    end

    head :no_content # answer fast, the job does the work
  rescue JSON::ParserError
    head :bad_request
  end
end
# app/jobs/process_inbound_mail_job.rb
class ProcessInboundMailJob < ApplicationJob
  queue_as :default

  def perform(message_id)
    mc = MailcycleClient.get
    message = mc.messages.get(message_id) # fetched by id, opened here
    return unless message.opened

    saved = save_attachments(mc, message, Rails.root.join("storage/inbound").to_s)
    Rails.logger.info("#{message.from_address}: #{message.subject} (#{saved.size} files)")
    mc.messages.mark_read(message.id, true)
  end

  private

  def save_attachments(mc, message, folder)
    target = File.join(folder, message.id)
    message.attachments.filter_map do |attachment|
      next unless attachment.stored
      next if attachment.content_id

      FileUtils.mkdir_p(target)
      name = File.basename(attachment.filename.tr("\\", "/"))
      name = "attachment" if name.empty? || name == "." || name == ".."
      path = File.join(target, "#{attachment.index}-#{name}")
      File.binwrite(path, mc.messages.attachment(message, attachment.index))
      path
    end
  end
end

What each part is for:

  • The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your whsec_ secret. Mailcycle.verify_webhook_signature checks it in constant time and refuses a timestamp more than five minutes old. Check the bytes as they arrived, with request.raw_post: a body that was parsed and re-encoded will not match.
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. The action replies first, and the fetching and saving happen in an ActiveJob.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. Rails.cache.write with unless_exist: true is an atomic claim on a shared cache such as Redis. With a per-process memory store, use a table with a unique constraint instead.

The same handler in Sinatra

require "sinatra"
require "json"
require "mailcycle"

MC = Mailcycle.sign_in(ENV.fetch("MAILCYCLE_PHRASE"))
SECRET = ENV.fetch("MAILCYCLE_WEBHOOK_SECRET")

post "/hooks/mailcycle" do
  raw = request.body.read
  signature = request.env["HTTP_MAILCYCLE_SIGNATURE"]
  halt 401, "bad signature" unless Mailcycle.verify_webhook_signature(SECRET, raw, signature)

  event = JSON.parse(raw)
  if event["type"] == "message.received"
    message_id = event.dig("payload", "messageId")
    Thread.new do
      message = MC.messages.get(message_id)
      puts "#{message.from_address}: #{message.subject}" if message.opened
    end
  end
  status 204
end

You can test a handler without a live webhook. Mailcycle.webhook_signature_header(secret, body, timestamp) builds the header Mailcycle would send. Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.

Ruby mail gem, Net::IMAP or an email API

The usual way to read mail in Ruby is Net::IMAP plus the mail gem: you give IMAP a host, port 993 and credentials, select the inbox, fetch each message’s raw source and hand it to Mail.new to parse. In Rails, Action Mailbox routes inbound mail to your app through an ingress such as Postfix or a provider’s webhook.

The Mailcycle gem is built for programs that need addresses of their own: one per customer, per test run or per agent, created in code, with each message handed over parsed and mail pushed to you as it arrives.

Net::IMAP and the mail gem Mailcycle Ruby gem
Install Standard library, plus mail for parsing gem install mailcycle
You need An IMAP mailbox and its credentials A recovery phrase, plus an API key if you want one
New addresses Made at your mail provider mc.addresses.create in code
Parsing Raw MIME, parsed by you Parsed fields: text, html, attachments
Tracker-free HTML Strip it yourself safe_html, with blocked listing what was removed
Attachments Walk the MIME parts mc.messages.attachment(message, index)
New-mail push IMAP IDLE Webhooks and mc.events.stream
Wait for one email Write the loop yourself wait_for
Mail at rest Depends on the provider Encrypted with keys from your recovery phrase

A Sidekiq or ActiveJob worker that waits

In a Rails app the wait belongs in a background job, so no web request holds a process while it listens. An ActiveJob keeps the code independent of the queue adapter.

class ReadSignupCodeJob < ApplicationJob
  queue_as :default

  def perform(user_id, address_id, since)
    message = MailcycleClient.get.messages.wait_for(
      address_id: address_id, subject: "verify", since: Time.iso8601(since), timeout: 60
    )
    code = message.text[/\b\d{6}\b/]
    User.find(user_id).update!(email_code: code)
  rescue Mailcycle::ApiError => e
    raise unless e.code == "timeout"
    retry_job wait: 30.seconds
  end
end

Enqueue it with the time taken before the sign-up request, as in ReadSignupCodeJob.perform_later(user.id, address.id, Time.now.iso8601), so the wait counts mail from that moment on. MailcycleClient.get is the initializer from the webhook section, so each worker process signs in once, and the phrase can come from Rails credentials or your platform’s secrets instead of ENV. A timeout is the quiet case, so the job retries rather than failing loudly.

An RSpec helper for sign-up emails

A shared context keeps the address lifecycle out of your examples:

RSpec.shared_context "with inbox" do
  let(:mc) { Mailcycle.sign_in(ENV.fetch("MAILCYCLE_PHRASE")) }
  let!(:address) { mc.addresses.create(prefix: "rspec", retention_days: 1) }
  after { mc.addresses.delete(address.id) }
end

RSpec.describe "sign up", type: :system do
  include_context "with inbox"

  it "emails a verification code" do
    since = Time.now
    visit "/signup"
    fill_in "Email", with: address.email_address
    click_button "Create account"
    message = mc.messages.wait_for(address_id: address.id, since: since, timeout: 60)
    expect(message.text).to match(/\b\d{6}\b/)
  end
end

Capybara drives the browser, and wait_for replaces the mail catcher that development setups often use, so the test covers your real provider.

Action Mailer in development, a real address in staging

Rails apps usually deliver to a catcher in development and to a provider in staging. Keep that split. In staging, point the sign-up form at an address from addresses.create and let the real delivery method run, so a misconfigured provider fails the check before a customer meets it.

A small Thor command

Ruby’s Thor makes a handy support tool: mail wait --subject receipt --timeout 90 creates an address, prints it, waits and writes the message text to the terminal. Exit with a non-zero status when the error code is timeout, so shell scripts can branch on it.

A Sinatra or Rack endpoint for webhooks

Not every Ruby service is Rails. A webhook receiver in Sinatra is a few lines, and the rule is the same: read the raw body before any parser touches it.

post "/hooks/mailcycle" do
  raw = request.body.read
  halt 401 unless Mailcycle.verify_webhook_signature(ENV.fetch("MAILCYCLE_WEBHOOK_SECRET"), raw, request.env["HTTP_MAILCYCLE_SIGNATURE"])
  event = JSON.parse(raw)
  ReadMessageJob.perform_async(event.dig("payload", "messageId")) if event["type"] == "message.received"
  status 204
end

Hand the message id to a job and return at once, so a slow handler never makes Mailcycle retry a delivery that already arrived. Rack exposes headers with an HTTP_ prefix and underscores, which is why the signature header is read as HTTP_MAILCYCLE_SIGNATURE.

Using Mail-style parsing on top of the SDK

Some Ruby teams already have code written around the mail gem’s message objects. You can keep that code by building a small adapter that wraps a Mailcycle message and exposes subject, from and text_part. The SDK has already decrypted and parsed the message, so the adapter is a handful of lines, and your downstream code never learns that the mail came from an API rather than IMAP. Keep the adapter in one file so a later SDK upgrade touches one place.

The Ruby email API at a glance

Every receiving call in this guide, in one place, as the gem names them in 0.3.1:

Task Call
Sign in, or pick up a saved session Mailcycle.sign_in(phrase), Mailcycle.resume(token, phrase)
Make an account and its phrase Mailcycle.create_account
Create, list and delete addresses mc.addresses.create, mc.addresses.list, mc.addresses.delete(id)
Read one page, or the whole folder mc.messages.list(address_id, limit:, cursor:), mc.messages.all(address_id)
Open one message mc.messages.get(message_id)
Download an attachment mc.messages.attachment(message, index)
Wait for the next match mc.messages.wait_for(address_id:, from:, subject:, since:, timeout:)
Change state mark_read, star, move_to, delete
Push new mail to your app mc.webhooks.create(url, events, name), mc.webhooks.test(id)
Check a delivery Mailcycle.verify_webhook_signature(secret, body, header)
Live events in a long-running process mc.events.stream

The same account also sends: mc.messages.send with reply_to: message answers in the thread, as the Ruby send email tutorial shows.

Troubleshooting

  • KeyError: key not found: "MAILCYCLE_PHRASE". The environment variable is not set in this shell or process. Export it as in Get a recovery phrase, or set it in your platform’s secrets.
  • e.code is "plan_required". The call needs a higher plan, such as webhooks on Operator. The error names the plan, e.upgrade_url links straight to the upgrade, and reading mail keeps working meanwhile.
  • e.code is "invalid_url" when you add a webhook. The URL is not HTTPS. Use an https tunnel while you develop, as in the webhook section.
  • A Rails webhook returns 401. Read request.raw_post before parameters are parsed, since the signature covers the exact bytes.
  • A job runs twice after a retry. Record the event id, enqueue and return, so a retried delivery never repeats the work.
  • Messages have opened set to false and empty fields. The client has no phrase, or a phrase from a different account. Build it with Mailcycle.sign_in(phrase).
  • Nothing arrives at a new address. Check address.receives in mc.addresses.list, and check the sender used the exact address, since prefixed names have a random ending.
  • e.code is "rate_limited". You are reading too much too fast. Back off, read only what is new, or switch to webhooks.
  • A 404 fetching an attachment. The part has stored set to false. Skip it.
  • The webhook action returns 401 for real deliveries. You are verifying a re-encoded body, or the wrong secret. Use request.raw_post and the whsec_ secret of this webhook.

Every error code is listed in Errors.

Reply from Ruby, or hand the inbox to an agent

To answer a message in the same thread, pass reply_to: message to mc.messages.send. Sending email from Ruby and Rails covers that, along with the plans that send.

If an AI agent should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox.

Next steps

FAQ

How do I receive email in Ruby?

Give your program an address that receives mail, then read it with a client. With Mailcycle, make a free account at https://app.mailcycle.email/operator/signup and keep its recovery phrase, run gem install mailcycle, sign in with Mailcycle.sign_in(phrase), create an address with mc.addresses.create, and call mc.messages.wait_for. The message comes back parsed and decrypted: sender, subject, text, HTML and attachments.

Is there a Ruby email API?

Yes. We provide the mailcycle gem, an Apache-2.0 Ruby SDK for the Mailcycle email API. It creates addresses, lists and reads messages, downloads attachments, waits for new mail, sends and replies, and manages webhooks and API keys, all over HTTPS. See the Ruby SDK page and the Ruby SDK guide.

Ruby mail gem or an email API: which should I use to receive email?

The mail gem parses a message once you have its raw text, so it is paired with Net::IMAP and a mailbox password. The mailcycle gem gives your program its own addresses and hands each message over already parsed, decrypted and stripped of trackers, with attachments one call away and new mail pushed to a webhook. For a program that needs inboxes of its own, the API is the shorter path.

Where does the recovery phrase come from?

It is made when the account is created: on the web at https://app.mailcycle.email/operator/signup, or in code with mc, phrase = Mailcycle.create_account. Keep the twelve words safe and pass them to your program in MAILCYCLE_PHRASE. If the variable is missing, ENV.fetch raises KeyError.

How do I read emails from an inbox in Ruby?

Call mc.messages.list(address.id, limit: 20) for one page, newest first, or mc.messages.all(address.id) to walk the whole inbox. Each message has from_address, subject, text, safe_html, attachments and read.

How do I download email attachments in Ruby?

Each message lists its files in message.attachments, with filename, mime_type, size and index. Call mc.messages.attachment(message, attachment.index) to get a binary String, opened on your machine, and write it with File.binwrite. Clean the file name first with File.basename, because it comes from the sender.

How can a Ruby program wait for a new email?

Call mc.messages.wait_for(address_id: ..., subject: ..., since: ..., timeout: ...). It returns the first matching message. If nothing matches in time it raises a Mailcycle::ApiError whose code is "timeout".

How do I get notified when an email arrives in a Rails app?

Add a webhook for message.received, point it at a controller action, and check each delivery with Mailcycle.verify_webhook_signature against request.raw_post. The event carries the message id, so fetch the message with mc.messages.get. Webhooks are on the Operator plan and above.

Is there a Ruby gem to read email without IMAP?

Yes. The mailcycle gem reads mail over HTTPS, so there is no IMAP host, port or mailbox password, and the message arrives already parsed.

Do I need Action Mailbox to receive email in Rails?

No. Action Mailbox takes mail through an ingress such as Postfix or a provider's webhook. With Mailcycle your app gets a small webhook with a message id, fetches the message, and reads it as Ruby objects, so there is no ingress to run.

Which Mailcycle plan do I need to receive email from Ruby?

Every plan can create addresses, read mail and download attachments when the program signs in with the recovery phrase. API keys and webhooks start at Operator. See Plans and limits.

Why does the Ruby client need my recovery phrase?

Mail is encrypted the moment it arrives, with keys from your recovery phrase. The gem derives the same keys on your machine and opens each message in your process. A message that does not open comes back with opened set to false.

Receive email in code