Class: Tolliver::Services::Methods::Email::Mailgun

Inherits:
Object
  • Object
show all
Defined in:
lib/tolliver/services/methods/email/mailgun.rb

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Mailgun

Returns a new instance of Mailgun.



18
19
20
21
22
23
24
25
# File 'lib/tolliver/services/methods/email/mailgun.rb', line 18

def initialize(params = {})
  require 'mailgun-ruby'
  if params[:api_key].blank? || params[:domain].blank?
    raise Tolliver::Errors::StandardError.new('Please provide API key and domain in e-mail provider params.')
  end
  @client = ::Mailgun::Client.new(params[:api_key])
  @domain = params[:domain]
end

Instance Method Details

#deliver(notification, notification_receiver) ⇒ Object



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
# File 'lib/tolliver/services/methods/email/mailgun.rb', line 27

def deliver(notification, notification_receiver)

  # Sender
  raise Tolliver::Errors::StandardError.new("Please specify e-mail sender.") if Tolliver.email_sender.nil?

  # Build message
  message = ::Mailgun::MessageBuilder.new
  message.from(Tolliver.email_sender, {'full_name' => Tolliver.email_sender_name})
  message.add_recipient(:to, notification_receiver.receiver_email.to_s)
  message.reply_to(notification_receiver.notification_delivery.sender_email.to_s) unless notification_receiver.notification_delivery.sender_email.blank?
  message.subject(notification.subject)
  message.body_text(ActionController::Base.helpers.strip_tags(notification.message.to_s))
  message.body_html(notification.message)
  notification.notification_attachments.each do |notification_attachment|
    message.add_attachment(StringIO.new(notification_attachment.read), notification_attachment.name) if notification_attachment.read
  end

  # Request API
  response = @client.send_message(@domain, message)
  if response.code != 200
    raise Tolliver::Errors::StandardError.new(response.body)
  end

  true
end