Created
September 5, 2016 01:28
-
-
Save iloveitaly/bbfa5ba4e1f193e4d0c75a8b032cdd7f to your computer and use it in GitHub Desktop.
Simple class to make it easy to send mail with Mandrill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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