forked from korki/mandrill_integration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mandrill_endpoint.rb
73 lines (63 loc) · 2.52 KB
/
mandrill_endpoint.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
Dir['./lib/**/*.rb'].each(&method(:require))
class MandrillEndpoint < EndpointBase::Sinatra::Base
set :logging, true
Honeybadger.configure do |config|
config.api_key = ENV['HONEYBADGER_KEY']
config.environment_name = ENV['RACK_ENV']
end
post '/send_email' do
# convert variables into Mandrill array / hash format.
#
unless (@payload.key? 'email')
add_value :payload_inspect, @payload.inspect
result 500, 'No Email Key found in Payload'
end
global_merge_vars = @payload['email'].fetch('variables', []).map do |name, value|
{ 'name' => name, 'content' => value }
end
template = @payload['email']['template']
merge_language = @payload['email']['merge_language']
to_addr = @payload['email']['to']
from_addr = @payload['email']['sender_email'] || @payload['email']['from']
from_name = @payload['email']['sender_name'] || from_addr
subject = @payload['email']['subject']
bcc_address = @payload['email']['bcc_address'] || ''
send_at = @payload['email']['send_at'] || ''
# create Mandrill request
#
request_body = {
key: @config['mandrill_api_key'],
template_name: template,
message: {
from_email: from_addr,
from_name: from_name,
to: to_addr.to_s.split(',').map { |email| { email: email } },
bcc_address: bcc_address,
subject: subject,
global_merge_vars: global_merge_vars
},
send_at: send_at,
template_content: [ name: 'User 1', content: 'Content 1' ]
}
# merge_language is optional
request_body[:message][:merge_language] = merge_language if merge_language.present?
# send request to Mandrill API
#
response = HTTParty.post('https://mandrillapp.com/api/1.0/messages/send-template.json',
body: request_body.to_json,
timeout: 240,
headers: { 'Content-Type' => 'application/json' })
#ugly because it could be a hash or an array
#https://mandrillapp.com/api/docs/messages.html
response = [response.parsed_response].flatten.first
reason = response['reject_reason'] || response['message'] || response.inspect
if %w{sent queued}.include?(response['status'])
set_summary "Sent '#{subject}' email to #{to_addr}"
add_value :mandrill_message_id, response["_id"]
process_result 200
else
set_summary "Failed to send '#{subject}' email to #{to_addr}. #{reason}"
process_result 500
end
end
end