Class: Incoming::Strategies::Mailgun

Inherits:
Object
  • Object
show all
Includes:
Incoming::Strategy
Defined in:
lib/incoming/strategies/mailgun.rb

Overview

Public: MailGun Incoming! Mail Strategy

API Documentation: documentation.mailgun.net/user_manual.html#receiving-messages

Examples:

class MailReceiver < Incoming::Strategies::Mailgun
  setup api_key: 'asdf'

  def receive(mail)
    puts "Got message from mailgun: #{mail.subject}"
  end
end

Instance Attribute Summary collapse

Attributes included from Incoming::Strategy

#message

Instance Method Summary collapse

Methods included from Incoming::Strategy

included, #receive

Constructor Details

#initialize(request) ⇒ Mailgun

Returns a new instance of Mailgun.



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
# File 'lib/incoming/strategies/mailgun.rb', line 30

def initialize(request)
  params = request.params

  if self.class.default_options[:api_key].nil?
    raise RequiredOptionError.new(':api_key option is required.')
  end

  @signature = params['signature']
  @token = params['token']
  @timestamp = params['timestamp']

  html_content = params[ self.class.default_options[:stripped] ? 'stripped-html' : 'body-html' ]
  text_content = params[ self.class.default_options[:stripped] ? 'stripped-text' : 'body-plain' ]

  if self.class.default_options[:stripped] && text_content.to_s == ''
    html_content = params['body-html']
    text_content = params['body-plain']
  end

  attachments = 1.upto(params['attachment-count'].to_i).map do |num|
    attachment_from_params(params["attachment-#{num}"])
  end

  @message = Mail.new do
    headers Hash[JSON.parse(params['message-headers'])]

    body text_content

    html_part do
      content_type 'text/html; charset=UTF-8'
      body html_content
    end if html_content

    attachments.each do |attachment|
      add_file(attachment)
    end
  end
end

Instance Attribute Details

#signatureObject

Returns the value of attribute signature.



28
29
30
# File 'lib/incoming/strategies/mailgun.rb', line 28

def signature
  @signature
end

#timestampObject

Returns the value of attribute timestamp.



28
29
30
# File 'lib/incoming/strategies/mailgun.rb', line 28

def timestamp
  @timestamp
end

#tokenObject

Returns the value of attribute token.



28
29
30
# File 'lib/incoming/strategies/mailgun.rb', line 28

def token
  @token
end

Instance Method Details

#authenticateObject



69
70
71
72
73
74
# File 'lib/incoming/strategies/mailgun.rb', line 69

def authenticate
  api_key = self.class.default_options[:api_key]

  hexdigest = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA256'), api_key, [timestamp, token].join)
  hexdigest.eql?(signature) or false
end