Send email with Ruby
Send a transactional email from Ruby with a single POST to /v1/email, authenticated with a Bearer API key. There is no official Ruby SDK, so you call the REST endpoint directly. The example below uses only the standard library, so there is no gem to install. See Send email via the API for the full field reference.
Prerequisites
- An API key, read from the
MAILHUSET_API_KEYenvironment variable. - A verified sending domain for the
fromaddress.
net/http
require 'net/http'
require 'uri'
require 'json'
uri = URI('https://api.mailhuset.com/v1/email')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV.fetch('MAILHUSET_API_KEY')}"
request['Content-Type'] = 'application/json'
request.body = {
from: 'Acme <hello@yourdomain.com>',
to: ['customer@example.com'],
subject: 'Your receipt',
html: '<p>Thanks for your order.</p>',
text: 'Thanks for your order.'
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
if response.is_a?(Net::HTTPSuccess)
message = JSON.parse(response.body)
puts "Accepted: #{message['id']}"
else
# 401 bad/missing key, 403 from-domain not verified, 422 validation error.
warn "Send failed (#{response.code}): #{response.body}"
endFields
Build the JSON body with the real fields: from (Name <address> on a verified domain), to (an array), subject, and the body as html and text (send both when you can). cc, bcc, replyTo (arrays) and idempotencyKey are optional. The full list is in Send email via the API.
Response
A 2xx returns the accepted message, including its id. Net::HTTPSuccess covers that range. Errors: 401 bad or missing key, 403 the from domain is not verified, 422 a validation error (the response says which field).
Next steps
Reuse content with Templates, and track delivery with Webhooks. Prefer a typed client? Node and Python have official SDKs.
Need help? Email support@mailhuset.com.