Skip to content

Instantly share code, notes, and snippets.

@adamcrown adamcrown/Gemfile
Created Nov 5, 2015

Embed
What would you like to do?
A basic mailer API intended to be used as a contact form backend for a static site.
require 'bundler'
Bundler.require :default
module Mailer
class Configuration
attr_accessor :recipient
end
def self.configure
yield config
end
def self.config
@config ||= Configuration.new
end
class Request
REQUIRED_PARAMS = ['name', 'email', 'message']
attr_reader :errors
def initialize(env)
@request = ::Rack::Request.new(env)
@errors = []
end
def valid?
missing = REQUIRED_PARAMS.select { |p| request.params[p].to_s == '' }
if missing.any?
@errors << "Missing #{missing.join(', ')}"
false
else
true
end
end
REQUIRED_PARAMS.each do |name|
define_method(name) do
@request.params[name]
end
end
private
attr_reader :request
end
class Email
attr_reader :to, :from, :name, :message
def initialize(from, name, message)
@from = from
@name = name
@message = message
end
def send!
mail = Mail.new
mail.from = from
mail.to = Mailer.config.recipient
mail.header['Reply-To'] = "#{name} <#{from}>"
mail.subject = subject
mail.body = body
mail.deliver!
end
private
def subject
"Submission from #{name} via Mailer"
end
def body
"From: #{name} <#{from}>\n\n#{message}\n\nEmail sent via Mailer"
end
end
class Rack
def self.call(env)
request = Mailer::Request.new(env)
if request.valid?
Email.new(request.email, request.name, request.message).send!
response 200, message: 'Message sent'
else
response 422, message: request.errors.join(', ')
end
rescue Exception => err
response 500, message: err.message
end
private
def self.response(status, body_hash)
body = body_hash.to_json
[status, {'Content-Type' => 'application/json', 'Content-Length' => body.size.to_s}, [body]]
end
end
end
Mailer.configure do |config|
config.recipient = ENV['MAILER_RECIPIENT']
end
run Mailer::Rack
source 'https://rubygems.org'
gem 'rack'
gem 'mail'
gem 'puma'
GEM
remote: https://rubygems.org/
specs:
mail (2.6.3)
mime-types (>= 1.16, < 3)
mime-types (2.6.2)
puma (2.14.0)
rack (1.6.4)
PLATFORMS
ruby
DEPENDENCIES
mail
puma
rack
BUNDLED WITH
1.10.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.