[Blog](https://sparetext.dev/blog)

# Send SMS from Ruby with Net::HTTP, through your own phone

No gem, no Twilio number: Ruby's own Net::HTTP sends the text from your phone. Then delivery status, safe retries, a CSV list and a webhook signature check for Rails, all run on Ruby 3.4.

Sparetext

6 min read · Nov 11, 2026

A lot of small businesses run on a Rails app someone built years ago: the booking system, the client portal, the shop. When it needs to send a text, the usual move is `gem install twilio-ruby`, a paid number, and a carrier registration form. If your texts go to people who already know you, Ruby's standard library and the phone in your pocket are enough.

Sparetext turns the Android phone you already own into an SMS gateway with a plain HTTP API. Your Ruby talks to our server, and the text goes out from your phone, on your number. Every sample below ran on 11 November on Ruby 3.4, against a test copy of Sparetext with a simulated phone on the other end.

## What you need

- A Sparetext account. Free is 1 phone and 300 texts a month.
- An Android phone with the Sparetext app, paired in the dashboard. An iPhone works too, through Sparetext for Mac ([the iPhone guide](https://sparetext.dev/iphone-sms-gateway)).
- An API key from the API keys page: `export SPARETEXT_API_KEY=spt_live_...` (in Rails, your credentials or environment, never the repo).
- Ruby 3.0 or later. `net/http`, `json`, `openssl` and `csv` all ship with it.

On a Mac, `/usr/bin/ruby` is still Apple's Ruby 2.6. The first sample runs on it, but the webhook check needs `OpenSSL.secure_compare`, which arrived with Ruby 3.0, and 2.6 stops with a NoMethodError there. Use Ruby from Homebrew, rbenv or asdf.

## Send your first text

send.rb

```ruby
require "net/http"
require "json"

uri = URI("https://sparetext.dev/api/v1/messages")
payload = { to: "+12025550174", text: "Your table for 2 is ready. See you soon!" }

res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
                      open_timeout: 5, read_timeout: 15) do |http|
  http.post(uri.path, payload.to_json,
            "x-api-key" => ENV.fetch("SPARETEXT_API_KEY"),
            "content-type" => "application/json")
end

body = JSON.parse(res.body)
abort "#{res.code} #{body["error"]["code"]}: #{body["error"]["message"]}" unless res.is_a?(Net::HTTPSuccess)
pp body["messages"].first.slice("id", "status", "deviceName")
```

Put your own number in `to`, with its country code, and run `ruby send.rb`. Ours printed the message `id`, `"status" => "queued"` and the phone's name, and the phone sends the text a moment later.

`Net::HTTP` doesn't raise on a 401 or a 500, it hands you the response, so the `is_a?(Net::HTTPSuccess)` check matters. `ENV.fetch` fails loudly when the key isn't set, which beats sending an empty header and wondering why. With a bad key ours printed `401 unauthorized: That key or token is not valid. It may have been revoked.`

## One module for every call

sparetext.rb

```ruby
require "net/http"
require "json"

module Sparetext
  API = URI("https://sparetext.dev/api/v1")

  # Every error the API sends: a code to test in code, a message for people.
  class Error < StandardError
    attr_reader :status, :code, :retry_after

    def initialize(status, code, message, retry_after)
      @status, @code, @retry_after = status, code, retry_after
      super("#{status} #{code}: #{message}")
    end
  end

  def self.call(method, path, payload = nil, headers = {})
    Net::HTTP.start(API.host, API.port, use_ssl: API.scheme == "https",
                    open_timeout: 5, read_timeout: 15) do |http|
      res = http.send_request(method, API.path + path, payload&.to_json, {
        "x-api-key" => ENV.fetch("SPARETEXT_API_KEY"),
        "content-type" => "application/json",
      }.merge(headers))
      body = res.body.to_s.empty? ? {} : JSON.parse(res.body)
      return body if res.is_a?(Net::HTTPSuccess)

      err = body.fetch("error", {})
      raise Error.new(res.code.to_i, err["code"], err["message"], res["retry-after"]&.to_i)
    end
  end
end
```

## Check that it arrived

`queued` means the text is waiting for your phone. It then moves to `dispatched` (the phone has it), `sent`, and `delivered` if your carrier sends delivery reports. A text that goes wrong ends at `failed`, with the reason in `error`.

status.rb

```ruby
require_relative "sparetext"

sent = Sparetext.call("POST", "/messages", to: "+12025550175", text: "Your order #1042 is out for delivery.")
id = sent["messages"].first["id"]
puts "#{id} #{sent["messages"].first["status"]}"

deadline = Time.now + 120
message = nil
loop do
  sleep 3
  message = Sparetext.call("GET", "/messages/#{id}")["message"]
  break if %w[delivered failed canceled].include?(message["status"]) || Time.now > deadline
end
puts [message["status"], message["error"]].compact.join(" ")
```

Against the simulated phone it printed `queued`, then `delivered` on the first check. A real phone on a real network takes longer, and some carriers never send a delivery report, so a text can rest at `sent`. In a Rails app, don't make a request wait for this: send from a background job, and let the webhook below tell you what happened.

## Retry without texting someone twice

Here's the thing about retries and SMS. If a request times out, you don't know whether the text was queued, and a blind retry can send it twice. The fix is an `Idempotency-Key` header: send the same key again and Sparetext hands back the first answer instead of queuing a second text, for 24 hours. Ruby's `retry` keyword makes this pleasantly short:

safe_send.rb

```ruby
require "securerandom"
require_relative "sparetext"

def send_text(payload, tries = 4)
  key = SecureRandom.uuid # the same key on every try, so a retry can't send twice
  attempt = 0
  begin
    attempt += 1
    Sparetext.call("POST", "/messages", payload, "idempotency-key" => key)
  rescue Sparetext::Error => e
    raise unless e.status == 429 && e.retry_after && attempt < tries # a bad number won't fix itself
    sleep e.retry_after
    retry
  rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError
    raise if attempt >= tries # timeout or network error: try again with the same key
    sleep attempt
    retry
  end
end
```

A small Ruby 3 trap we stepped in: our first version took `tries:` as a keyword argument. Then `send_text(messages: chunk)` blew up with `wrong number of arguments (given 0, expected 1)`, because Ruby 3 read `messages:` as a keyword too. A plain positional `tries = 4` avoids it.

Then we checked it. The same key sent twice came back with the same message id, and only one text was queued; the same key with different words got `422 idempotency_mismatch`. An account can make 15 send requests every 5 seconds, then hears `429 rate_limited` with `Retry-After`. Thirty texts in a row through `send_text` all went through in about 14 seconds, waiting as told. The one 429 without `Retry-After` is `key_daily_limit`, and that one is raised, not retried.

## Text a list from a CSV

batch.rb

```ruby
require "csv"
require_relative "safe_send"

messages = CSV.foreach("bookings.csv", headers: true).map do |b|
  { to: b["phone"], text: "Hi #{b["name"]}, see you tomorrow at #{b["time"]}. Reply YES to confirm." }
end

messages.each_slice(100) do |chunk|
  batch = send_text(messages: chunk)
  puts "#{batch["batchId"]}: #{batch["messages"].size} queued, last one out about #{batch["estimatedCompletionAt"]}"
end
```

`each_slice(100)` matches the API's limit of 100 texts per request. Your phone sends about 30 a minute, under Android's own limit, so `estimatedCompletionAt` is worth printing for a long list. The three made-up guests in our file answered YES a few seconds later, and this reads them back:

replies.rb

```ruby
require "time"
require_relative "sparetext"

since = (Time.now - 10 * 60).utc.iso8601
replies = Sparetext.call("GET", "/messages?" + URI.encode_www_form(direction: "inbound", since: since))

replies["messages"].each { |text| puts "#{text["contact"]} said: #{text["text"]}" }
```

## Check a webhook's signature

For an app, a webhook beats polling: Sparetext posts each text your phone receives to your URL. Anyone who finds that URL can post to it too, so check the `X-Sparetext-Signature` header first. It looks like `t=1793438045,v1=9c2f…`: a timestamp, then an HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the webhook's secret.

webhook.rb

```ruby
require "openssl"

# True when a request really came from Sparetext. Pass the body exactly as it arrived.
def from_sparetext?(raw, header, secret, now: Time.now.to_i)
  t = header[/(?:\A|,)t=(\d+)/, 1]
  return false if t.nil? || (now - t.to_i).abs > 300 # missing, or a replayed old request

  want = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw}")
  header.scan(/v1=([0-9a-f]{64})/).flatten.any? { |got| OpenSSL.secure_compare(want, got) }
end
```

In a Rails controller, pass it `request.raw_post` and `request.headers["X-Sparetext-Signature"].to_s`, return `head :unauthorized` when it's false, and skip CSRF protection for that one action, since Sparetext can't send your form token. Use the raw body, not `params`: the signature covers the exact bytes, and parsed params won't hash the same.

To test it, we captured a real signed delivery from Sparetext and ran the function on it: `true`. With a wrong secret, one changed word in the body, a clock ten minutes later, or no header at all, it said `false` every time. (The `now:` argument exists for exactly that kind of test.) We didn't run it inside a Rails app, so treat the controller part as the usual Rails wiring. [The webhook guide](https://sparetext.dev/receive-sms-webhook) has every event and how retries work.

## What this can't do

A phone is the right tool for texts to people who know you: reminders, confirmations, alerts to your team, replies to customers. For login codes there's a ready-made [verify endpoint](https://sparetext.dev/sms-otp-verification), so you don't store codes yourself.

It's the wrong tool for marketing to a list that didn't ask. Carriers filter business texts sent by software even from a personal number, and [the 10DLC post](https://sparetext.dev/blog/send-sms-without-10dlc) explains why. An iPhone can't send silently in the background the way Android can, and only Android phones get carrier delivery reports. On plans, Free covers 300 texts a month and Pro 10,000 on up to 5 phones ([pricing](https://sparetext.dev/pricing)).

The same steps exist for [Python](https://sparetext.dev/blog/send-sms-from-python), [Node.js](https://sparetext.dev/blog/send-sms-from-node-js), [PHP](https://sparetext.dev/blog/send-sms-from-php), [Go](https://sparetext.dev/blog/send-sms-from-go) and [Java](https://sparetext.dev/blog/send-sms-from-java). For a quick alert from a server, [curl in a bash script](https://sparetext.dev/blog/send-sms-from-bash-with-curl) is enough.

## Try it with your own number

Make a key on the API keys page, pair your phone, and run `ruby send.rb` with your own number in `to`. When your pocket buzzes, move `Sparetext.call` and `send_text` into a background job and send the first real reminder.

ruby rails send sms sms api net/http webhooks tutorial

Try it with the phone you have

Free for 1 phone and 300 texts a month. Pair it in about two minutes.

[Start free](https://sparetext.dev/signup)

## Responses

[Sign in](https://sparetext.dev/login?next=%2Fblog%2Fsend-sms-from-ruby%23responses) or [create an account](https://sparetext.dev/signup?next=%2Fblog%2Fsend-sms-from-ruby%23responses) to respond.

## More from the blog

- **[Your first text from code in five minutes, timed against Twilio's steps](https://sparetext.dev/blog/first-text-from-code-in-five-minutes)**
   5 min read
- **[Uptime Kuma SMS alerts from your own phone, with one webhook](https://sparetext.dev/blog/uptime-kuma-sms-alerts)**
   6 min read
- **[We handed our dashboard to two AI agents: this week in Sparetext](https://sparetext.dev/blog/we-handed-our-dashboard-to-two-ai-agents)**
   5 min read

---

This is the Markdown copy of https://sparetext.dev/blog/send-sms-from-ruby for AI agents. Every public page has one: add .md to its address (the home page is https://sparetext.dev/index.md). Sparetext for agents in one file: https://sparetext.dev/llms.txt
