Class: Mailgun::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/mailgun/client.rb

Overview

A Mailgun::Client object is used to communicate with the Mailgun API. It is a wrapper around Faraday so you don’t have to worry about the HTTP aspect of communicating with our API.

See the Github documentation for full examples.

Constant Summary collapse

SUBACCOUNT_HEADER =
'X-Mailgun-On-Behalf-Of'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key = Mailgun.api_key, api_host = Mailgun.api_host || 'api.mailgun.net', api_version = Mailgun.api_version || 'v3', ssl = true, test_mode = !Mailgun.test_mode.nil?,, timeout = nil, proxy_url = Mailgun.proxy_url) ⇒ Client

Returns a new instance of Client.



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
# File 'lib/mailgun/client.rb', line 12

def initialize(api_key = Mailgun.api_key,
               api_host = Mailgun.api_host || 'api.mailgun.net',
               api_version = Mailgun.api_version || 'v3',
               ssl = true,
               test_mode = !Mailgun.test_mode.nil?,
               timeout = nil,
               proxy_url = Mailgun.proxy_url)
  endpoint = endpoint_generator(api_host, api_version, ssl)

  request_options = {
    url: endpoint,
    proxy: proxy_url,
    ssl: { verify: ssl },
    headers: {
      'User-Agent' => "mailgun-sdk-ruby/#{Mailgun::VERSION}",
      'Accept' => '*/*'
    }
  }
  request_options.merge!(request: { timeout: timeout }) if timeout

  @http_client = build_http_client(api_key, request_options)

  @test_mode = test_mode
  @api_version = api_version
end

Instance Attribute Details

#api_versionString (readonly)

Returns client api version.

Returns:

  • (String)

    client api version



75
76
77
# File 'lib/mailgun/client.rb', line 75

def api_version
  @api_version
end

Class Method Details

.deliveriesHash

Provides a store of all the emails sent in test mode so you can check them.

Returns:

  • (Hash)


80
81
82
# File 'lib/mailgun/client.rb', line 80

def self.deliveries
  @@deliveries ||= []
end

Instance Method Details

#delete(resource_path, params = nil, body_params = false) ⇒ Mailgun::Response

Generic Mailgun DELETE Handler

with. Be sure to include your domain, where necessary.

Parameters:

  • resource_path (String)

    This is the API resource you wish to interact

Returns:



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/mailgun/client.rb', line 176

def delete(resource_path, params = nil, body_params = false)
  response =
    if params
      if body_params
        @http_client.delete(resource_path) do |request|
          request.body = params.to_json
        end
      else
        @http_client.delete(resource_path, params: params)
      end
    else
      @http_client.delete(resource_path)
    end
  Response.new(response)
rescue StandardError => e
  raise communication_error e
end

#disable_test_mode!Object

Disable test mode

Reverts the test_mode flag and allows the client to send messages.



48
49
50
# File 'lib/mailgun/client.rb', line 48

def disable_test_mode!
  @test_mode = false
end

#enable_test_mode!Object

Enable test mode

Prevents sending of any messages.



41
42
43
# File 'lib/mailgun/client.rb', line 41

def enable_test_mode!
  @test_mode = true
end

#get(resource_path, params = {}, accept = '*/*') ⇒ Mailgun::Response

Generic Mailgun GET Handler

Parameters:

  • resource_path (String)

    The API resource path to request, including the domain if required.

  • params (Hash) (defaults to: {})

    Optional request parameters, including query parameters and headers.

    • :headers [Hash] (optional) Custom headers for the request.

  • accept (String) (defaults to: '*/*')

    The expected Content-Type of the response. Defaults to ‘/’.

Returns:

Raises:



148
149
150
151
152
153
154
155
# File 'lib/mailgun/client.rb', line 148

def get(resource_path, params = {}, accept = '*/*')
  headers = (params[:headers] || {}).merge(accept: accept)
  response = @http_client.get(resource_path, params, headers)

  Response.new(response)
rescue StandardError => e
  raise communication_error(e)
end

#post(resource_path, data, headers = {}) ⇒ Mailgun::Response

Generic Mailgun POST Handler

with. Be sure to include your domain, where necessary. containing required parameters for the requested resource.

Parameters:

  • resource_path (String)

    This is the API resource you wish to interact

  • data (Hash)

    This should be a standard Hash

  • headers (Hash) (defaults to: {})

    Additional headers to pass to the resource.

Returns:



133
134
135
136
137
138
# File 'lib/mailgun/client.rb', line 133

def post(resource_path, data, headers = {})
  response = @http_client.post(resource_path, data, headers)
  Response.new(response)
rescue StandardError => e
  raise communication_error e
end

#put(resource_path, data, headers = {}) ⇒ Mailgun::Response

Generic Mailgun PUT Handler

with. Be sure to include your domain, where necessary. containing required parameters for the requested resource.

Parameters:

  • resource_path (String)

    This is the API resource you wish to interact

  • data (Hash)

    This should be a standard Hash

Returns:



164
165
166
167
168
169
# File 'lib/mailgun/client.rb', line 164

def put(resource_path, data, headers = {})
  response = @http_client.put(resource_path, data, headers)
  Response.new(response)
rescue StandardError => e
  raise communication_error e
end

#reset_subaccountObject

Reset subaccount for primary usage



63
64
65
# File 'lib/mailgun/client.rb', line 63

def reset_subaccount
  @http_client.headers.delete(SUBACCOUNT_HEADER)
end

#send_message(working_domain, data) ⇒ Mailgun::Response

Simple Message Sending

containing required parameters for the requested resource.

Parameters:

  • working_domain (String)

    This is the domain you wish to send from.

  • data (Hash)

    This should be a standard Hash

Returns:



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/mailgun/client.rb', line 90

def send_message(working_domain, data)
  perform_data_validation(working_domain, data)

  if test_mode?
    Mailgun::Client.deliveries << data.dup
    return Response.from_hash(
      {
        body: "{\"id\": \"test-mode-mail-#{SecureRandom.uuid}@localhost\", \"message\": \"Queued. Thank you.\"}",
        status: 200
      }
    )
  end

  case data
  when Hash
    # Remove nil values from the data hash
    # Submitting nils to the API will likely cause an error.
    #  See also: https://github.com/mailgun/mailgun-ruby/issues/32
    data = data.reject { |_k, v| v.nil? }

    if data.key?(:message)
      if data[:message].is_a?(String)
        file = convert_string_to_file(data[:message])
        data[:message] = Faraday::Multipart::FilePart.new(file, 'multipart/form-data')
      end
      return post("#{working_domain}/messages.mime", data)
    end
    post("#{working_domain}/messages", data)
  when MessageBuilder
    post("#{working_domain}/messages", data.message)
  else
    raise ParameterError.new('Unknown data type for data parameter.', data)
  end
end

#set_api_key(api_key) ⇒ Object

Change API key



53
54
55
# File 'lib/mailgun/client.rb', line 53

def set_api_key(api_key)
  @http_client.set_basic_auth('api', api_key)
end

#set_subaccount(subaccount_id) ⇒ Object

Add subaccount id to headers



58
59
60
# File 'lib/mailgun/client.rb', line 58

def set_subaccount(subaccount_id)
  @http_client.headers.merge!({ SUBACCOUNT_HEADER => subaccount_id })
end

#suppressions(domain) ⇒ Mailgun::Suppressions

Constructs a Suppressions client for the given domain.

Parameters:

  • domain (String)

    Domain which suppressions requests will be made for

Returns:



198
199
200
# File 'lib/mailgun/client.rb', line 198

def suppressions(domain)
  Suppressions.new(self, domain)
end

#test_mode?Boolean

Client is in test mode?

Returns:

  • (Boolean)

    Is the client set in test mode?



70
71
72
# File 'lib/mailgun/client.rb', line 70

def test_mode?
  @test_mode
end