Send with

Send email with Rails

Keep writing mailers the Rails way. A small delivery method hands each message to the Robust Email API instead of an SMTP server, so your mailers, views, attachments and deliver_later all keep working.

The delivery method

# lib/robust_email_delivery.rb
require "net/http"
require "json"

class RobustEmailDelivery
  API = URI("https://robustemail.com/api/v2/emails")

  attr_accessor :settings

  def initialize(settings)
    @settings = settings
  end

  def deliver!(mail)
    request = Net::HTTP::Post.new(API)
    request["Authorization"] = "Bearer #{settings.fetch(:api_key)}"
    request["Content-Type"] = "application/json"
    # Set headers["Idempotency-Key"] in a mailer to make retries safe
    key = mail["Idempotency-Key"]&.value
    request["Idempotency-Key"] = key if key
    request.body = payload(mail).to_json

    response = Net::HTTP.start(API.host, API.port, use_ssl: true, read_timeout: 15) do |http|
      http.request(request)
    end
    body = JSON.parse(response.body)
    raise "Robust Email #{body['name']}: #{body['message']}" unless response.is_a?(Net::HTTPSuccess)

    body
  end

  private

  def payload(mail)
    data = {
      from: mail[:from].to_s,
      to: mail.to,
      cc: mail.cc,
      bcc: mail.bcc,
      reply_to: mail.reply_to,
      subject: mail.subject
    }

    if mail.multipart?
      data[:html] = mail.html_part&.decoded
      data[:text] = mail.text_part&.decoded
    elsif mail.mime_type == "text/html"
      data[:html] = mail.decoded
    else
      data[:text] = mail.decoded
    end

    attachments = mail.attachments.map do |file|
      { filename: file.filename, content: [file.decoded].pack("m0"), content_type: file.mime_type }
    end
    data[:attachments] = attachments if attachments.any?

    data.compact
  end
end

Register it

# config/initializers/robust_email.rb
require Rails.root.join("lib/robust_email_delivery")

ActionMailer::Base.add_delivery_method :robust_email, RobustEmailDelivery,
  api_key: ENV.fetch("ROBUSTEMAIL_API_KEY")
# config/environments/production.rb
config.action_mailer.delivery_method = :robust_email

Use a rb_test_ key in staging: requests are checked and logged, but nothing is delivered.

Use your mailers as usual

class UserMailer < ApplicationMailer
  default from: "Acme <hello@acme.com>"

  def welcome(user)
    @user = user
    headers["Idempotency-Key"] = "welcome-user-#{user.id}"
    mail(to: user.email, subject: "Welcome to Acme")
  end
end

UserMailer.welcome(user).deliver_later

The Idempotency-Key header is sent to the API, not inside the email. If Active Job retries the delivery, the API returns the first email instead of sending a second one.

Next