Class: Mailgarage::DeliveryMethod

Inherits:
Object
  • Object
show all
Defined in:
lib/mailgarage/delivery_method.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ DeliveryMethod

Returns a new instance of DeliveryMethod.



5
6
7
8
# File 'lib/mailgarage/delivery_method.rb', line 5

def initialize(options = {})
  @settings = options
  @api_key = Mailgarage.configuration.api_key
end

Instance Method Details

#deliver!(mail) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mailgarage/delivery_method.rb', line 10

def deliver!(mail)
  @mail = mail

  case Rails.env
  when 'development'
    deliver_in_development
  when 'production'
    deliver_in_production
  when 'test'
    deliver_in_test
  else # any arbitrary env like staging
    deliver_in_production
  end
end

#deliver_in_developmentObject



41
42
43
44
45
46
47
# File 'lib/mailgarage/delivery_method.rb', line 41

def deliver_in_development
  LetterOpener::DeliveryMethod.new(
    message_template: 'light',
    location: Rails.root.join('tmp', 'mailgarage')
  )
  .deliver!(@mail)
end

#deliver_in_productionObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/mailgarage/delivery_method.rb', line 25

def deliver_in_production
  raise(Mailgarage::Error, "We can't send emails in #{Rails.env} without api_key set.") unless @api_key

  uri = URI.parse('https://mailgarage.rocks')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new('/emails')
  request.body = { email: @mail.to_s, environment: Rails.env }.to_json
  request['Content-Type'] = 'application/json'
  request['Api-Key'] = @api_key
  http.request(request)
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
  Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
  raise(Mailgarage::Error, "Error from Net::HTTP: #{e.message}")
end

#deliver_in_testObject

Raises:



49
50
51
# File 'lib/mailgarage/delivery_method.rb', line 49

def deliver_in_test
  raise(Mailgarage::Error, 'You should set config.mail_delivery to :test in your environment config so you can test your email delivery.')
end