Send email from Rails with Shipmail
Add Shipmail as an Action Mailer delivery method. Your mailers, deliver_now and deliver_later then send through the Shipmail API without other changes.
Last updated
Before you start
- A verified sending subdomain, such as
notify.example.com, with an active sender. See Transactional email. - An API key with send access to the sender's mailbox.
- The sender address, such as
hello@notify.example.com. Use the bare address. Shipmail adds the sender name.
Add the delivery method
Save it as config/initializers/shipmail.rb. It posts each email to the API with the bare From address, because Shipmail adds the sender name. If the mail sets an Idempotency-Key header, the class passes it on. It raises RateLimited on a 429 and Error on any other refusal.
# config/initializers/shipmail.rb
require "net/http"
class ShipmailDelivery
class RateLimited < StandardError; end
class Error < StandardError; end
URL = URI("https://shipmail.to/api/v1/messages")
def initialize(settings)
@api_key = settings.fetch(:api_key)
end
def deliver!(mail)
request = Net::HTTP::Post.new(URL)
request["Authorization"] = "Bearer #{@api_key}"
request["Content-Type"] = "application/json"
key = mail["Idempotency-Key"]&.value
request["Idempotency-Key"] = key if key
request.body = payload(mail).to_json
response = Net::HTTP.start(URL.host, URL.port, use_ssl: true) do |http|
http.request(request)
end
return if response.is_a?(Net::HTTPSuccess)
error = response.code == "429" ? RateLimited : Error
raise error, "Shipmail returned #{response.code}: #{response.body}"
end
private
def payload(mail)
text = mail.text_part || (mail if mail.mime_type == "text/plain")
html = mail.html_part || (mail if mail.mime_type == "text/html")
{
from: mail.from.first,
to: mail.to,
cc: mail.cc,
bcc: mail.bcc,
subject: mail.subject,
text: text&.decoded,
html: html&.decoded,
}.compact
end
end
ActionMailer::Base.add_delivery_method :shipmail, ShipmailDelivery,
api_key: ENV["SHIPMAIL_API_KEY"]Make it the default
Select it in each environment that should send real email, and set the key.
# config/environments/production.rb
config.action_mailer.delivery_method = :shipmail
config.action_mailer.raise_delivery_errors = trueSHIPMAIL_API_KEY=sm_live_...Send from a mailer
Give each email a key built from your own record. Shipmail keeps each key for 24 hours and sends a repeated key once, so a retried job does not send the welcome email twice. See Idempotency.
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
default from: "hello@notify.example.com"
def welcome(user)
@user = user
mail(
to: user.email,
subject: "Welcome to Acme",
"Idempotency-Key" => "welcome-#{user.id}",
)
end
endUserMailer.welcome(user).deliver_laterRetry when rate limited
deliver_later runs in ActionMailer::MailDeliveryJob. A subclass with retry_on tries again a minute after a 429. The retry sends the same key, so the email goes out once. See Rate limits.
# app/jobs/shipmail_delivery_job.rb
class ShipmailDeliveryJob < ActionMailer::MailDeliveryJob
retry_on ShipmailDelivery::RateLimited, wait: 1.minute, attempts: 5
end
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
self.delivery_job = ShipmailDeliveryJob
endTest without sending
Use a sm_test_ key while you build. Shipmail accepts the request, delivers nothing and lists the send under Test in Activity. See Sandbox mode.