Class: MailgunClient

Inherits:
Object
  • Object
show all
Defined in:
lib/email_api/email/client/mailgun_client.rb

Overview

Client for sending email via Mailgun v3 API

Class Method Summary collapse

Class Method Details

.bad_req_codeObject

Accessor for the Bad Request Code



24
25
26
# File 'lib/email_api/email/client/mailgun_client.rb', line 24

def self.bad_req_code
  @bad_req_code
end

.exp_msgObject

Accessor for the expected success message



14
15
16
# File 'lib/email_api/email/client/mailgun_client.rb', line 14

def self.exp_msg
  @exp_msg
end

.internal_err_codeObject

Accessor for the Internal Server Error Code



29
30
31
# File 'lib/email_api/email/client/mailgun_client.rb', line 29

def self.internal_err_code
  @internal_err_code
end

.ok_codeObject

Accessor for the OK Code



19
20
21
# File 'lib/email_api/email/client/mailgun_client.rb', line 19

def self.ok_code
  @ok_code
end

.send_email(email_object) ⇒ Response

Sends an email over HTTPS



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
# File 'lib/email_api/email/client/mailgun_client.rb', line 37

def self.send_email(email_object)

  # Build Mailgun-specific URL and POST data
  api_key = ENV['MAILGUN_PRIVATE_KEY']
  domain  = ENV['MAILGUN_DOMAIN']
  return internal_err_code if api_key.nil? || domain.nil?

  post_data = parse_post_data(email_object, domain)
  return bad_req_code if post_data.nil?

  url = "https://api:#{api_key}@api.mailgun.net/v3/#{domain}/messages"

  # Send Email, return response
  begin
    response = RestClient.post url, post_data
  rescue StandardError => e
    # Log error and fail send -> occurs when Code 400 due to implementation
    puts "Error: #{e.message}"
    return bad_req_code
  end

  puts "Secondary Client Response: #{response}"

  # Handle expected output. Note that it is API specific.
  return ok_code if JSON.parse(response)['message'] == exp_msg

  bad_req_code
end