Skip to content

Instantly share code, notes, and snippets.

@iloveitaly
Created September 5, 2016 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iloveitaly/bbfa5ba4e1f193e4d0c75a8b032cdd7f to your computer and use it in GitHub Desktop.
Save iloveitaly/bbfa5ba4e1f193e4d0c75a8b032cdd7f to your computer and use it in GitHub Desktop.
Simple class to make it easy to send mail with Mandrill
require 'mandrill'
class MandrillMailer
include SimpleStructuredLogger
def self.mail(*args)
self.new.mail(*args)
end
def mail(email:, template:, vars:)
result = mandrill.messages.send_template(
template,
[],
build_message(email, vars)
)
result = result.first
if result['status'] != 'sent'
fail "message failed to send: status=#{result['status']} reason=#{result['reject_reason']}"
end
log.info 'email sent',
template: template,
email: email,
ns_order_id: vars['id']
end
private
def mandrill
@mandrill ||= Mandrill::API.new
end
def build_vars_for_mandrill(attributes)
attributes.map do |key, value|
{
name: key,
content: value
}
end
end
# TODO add first and last name for improved deliverability
def build_message(email, vars)
{
to: [
{
"email": email,
"type": "to"
}
],
merge_language: "handlebars",
merge: true,
global_merge_vars: build_vars_for_mandrill(vars),
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment