# Send, receive and test email with Ruby

Most Ruby applications send email at the moments that matter to a customer: signup confirmation, password reset, order receipts and account alerts. Checking those emails in a test takes three things a normal mailbox doesn't give you: an address the test controls, a wait that ends as soon as the message arrives instead of a fixed `sleep`, and the subject, body, links and codes as data the test can assert on. A shared inbox or a mail catcher on one machine also breaks down in CI, where tests run in parallel and mail goes through your real sending provider.

MailSlurp is an email and SMS API built for this. The `mailslurp_client` gem creates inboxes on demand, sends email from them, waits for incoming messages and returns each email as a Ruby object, so a test can check the exact message your application sent. The same inboxes work over [SMTP and IMAP](/docs/imap-smtp/), and [webhooks](/docs/webhooks/) can notify your application when mail arrives.

## Quick links

| Task | Start here |
| --- | --- |
| Install the gem and create an inbox | [Get started](#get-started) |
| Wait for an email and read a code | [Receive email](#receive-email) |
| Test a signup email in RSpec | [Test with RSpec](#test-with-rspec) |
| Check the email a Rails app sends | [Rails and SMTP](#rails-and-smtp) |
| Find a Ruby method and its arguments | [Ruby method reference](https://ruby.mailslurp.com/) |
| Find current HTTP endpoints and request fields | [REST API reference](/docs/api/) |
| Find runnable projects | [RSpec](https://github.com/mailslurp/examples/tree/master/ruby-rspec), [Cucumber](https://github.com/mailslurp/examples/tree/master/ruby-cucumber-test), [Capybara with Selenium](https://github.com/mailslurp/examples/tree/master/ruby-capybara-cucumber-selenium) and [Minitest with Net::SMTP](https://github.com/mailslurp/examples/tree/master/ruby-minitest-netsmtp-example) |
| Check the released gem | [RubyGems package](https://rubygems.org/gems/mailslurp_client) |

The [Ruby SDK reference](/docs/ruby/) documents the generated client. The examples below use `mailslurp_client` 17.5.0.

## Get started

### Create an API key

Copy an API key from the [MailSlurp dashboard](https://app.mailslurp.com). Store it in your environment as `MAILSLURP_API_KEY`. For an organization or a support-provided demo, use the key belonging to that account.

### Install the gem

Add the gem to your `Gemfile` and run `bundle install`:

```ruby
gem "mailslurp_client", "~> 17.5"
```

Without Bundler, run `gem install mailslurp_client`. Pin the version you validate so a later release can't change a method signature under your tests.

### Configure and create an inbox

This complete script creates an inbox and prints its ID and address:

```ruby
require "mailslurp_client"

MailSlurpClient.configure do |config|
  config.api_key["x-api-key"] = ENV.fetch("MAILSLURP_API_KEY")
  config.timeout = 60
end

inboxes = MailSlurpClient::InboxControllerApi.new
inbox = inboxes.create_inbox_with_defaults
puts "Inbox ID: #{inbox.id}"
puts "Send your test email to: #{inbox.email_address}"
```

`config.timeout` is the HTTP time limit in seconds. The client has no limit by default, so set one that is longer than any wait you ask the API for. Use the address the API returns; its domain depends on your account and inbox settings.

## Email usage examples

### Receive email

Send an email from the application you are testing to the address above. Set `MAILSLURP_INBOX_ID` to the returned inbox ID, then, after the `configure` block, run:

```ruby
waiting = MailSlurpClient::WaitForControllerApi.new
email = waiting.wait_for_latest_email(
  inbox_id: ENV.fetch("MAILSLURP_INBOX_ID"),
  timeout: 30_000,
  unread_only: true
)
puts email.subject
puts email.body

code = email.body[/\b\d{6}\b/]
```

The API waits up to 30 seconds (`timeout` is in milliseconds) and returns as soon as a new email arrives. `unread_only: true` skips messages an earlier step already read. The regular expression reads a six-digit code from the body. To match a particular sender or subject, or to wait for several messages, see [waiting for email](/docs/wait-for/). For confirmation links, see [email verification](/docs/verification/).

### Create an inbox with options

Use `CreateInboxDto` to name an inbox or set other options:

```ruby
inbox = inboxes.create_inbox_with_options(
  MailSlurpClient::CreateInboxDto.new(name: "Checkout test")
)
```

### Send emails

For an account with sending enabled, send from an inbox with `SendEmailOptions`:

```ruby
inboxes.send_email(
  inbox.id,
  MailSlurpClient::SendEmailOptions.new(
    to: [ENV.fetch("TEST_RECIPIENT")],
    subject: "Order confirmation",
    body: "<h1>Thank you for your order</h1>",
    is_html: true
  )
)
```

See [sending and receiving email](/docs/emails/) for message options and [attachments](/docs/attachments/) for uploads and downloads.

### Delete an inbox

Delete a test inbox once your assertions finish:

```ruby
inboxes.delete_inbox(inbox.id)
```

For inbox expiry and cleanup across parallel test runs, see [test resource lifecycle](/docs/test-resource-lifecycle/).

## Test with RSpec

This spec gives each example its own inbox, waits for the email and checks the code. Because every example has a separate address, parallel runs never read one another's mail.

```ruby
require "mailslurp_client"

MailSlurpClient.configure do |config|
  config.api_key["x-api-key"] = ENV.fetch("MAILSLURP_API_KEY")
  config.timeout = 60
end

RSpec.describe "signup email" do
  let(:inboxes) { MailSlurpClient::InboxControllerApi.new }
  let(:waiting) { MailSlurpClient::WaitForControllerApi.new }
  let!(:inbox) { inboxes.create_inbox_with_defaults }

  after { inboxes.delete_inbox(inbox.id) }

  it "sends a verification code" do
    # Replace this with the step that makes your application send its email.
    inboxes.send_email(
      inbox.id,
      MailSlurpClient::SendEmailOptions.new(
        to: [inbox.email_address],
        subject: "Verify your account",
        body: "Your verification code is 482913"
      )
    )

    email = waiting.wait_for_latest_email(
      inbox_id: inbox.id,
      timeout: 30_000,
      unread_only: true
    )

    expect(email.subject).to eq("Verify your account")
    expect(email.body[/\b\d{6}\b/]).to eq("482913")
  end
end
```

As written, the spec sends the email itself so you can run it straight away with `bundle exec rspec`. In your own test, replace the `send_email` call with the action that triggers your application's email, such as submitting the signup form with `inbox.email_address` or calling the service that sends it.

## Rails and SMTP

In a Rails test environment, Action Mailer's `:test` delivery method keeps mail in `ActionMailer::Base.deliveries` and sends nothing. That checks your mailer code, not delivery. To check the email a customer receives, run the test against an environment that sends through your real provider and use a MailSlurp inbox address as the recipient. The [Rails email testing walkthrough](/blog/testing-real-emails-ruby-on-rails/) covers a complete application.

If your code sends with `Net::SMTP` or Action Mailer's SMTP settings, see [sending email over SMTP in Ruby](/guides/smtp/ruby-send-email-smtp/) and [SMTP and IMAP access](/docs/imap-smtp/).

## Render the email on real devices

Once MailSlurp has received the email, `email.id` identifies it for [device rendering](/docs/device-renders/#create-runs-from-stored-email), which captures screenshots of that exact message in Gmail, Outlook, Apple Mail and other clients. See [render CI checks](/docs/device-rendering-ci/) for waiting on a run and failing a build when a target doesn't complete.

## SDK Documentation

Use the [Ruby method reference](https://ruby.mailslurp.com/) for published controller methods and the [REST reference](/docs/api/) for current endpoints. The [generated Ruby reference files on GitHub](https://github.com/mailslurp/mailslurp-client-ruby/tree/master/docs) list each method's arguments; select the tag that matches your installed gem before copying method names. The example projects each pin the gem version they were written for, so check their calls against your installed version.

For message waits, OTPs, links and CI assertions in other frameworks, continue with [integration testing](/docs/testing/).
