Class: Mailosaur::Messages

Inherits:
Object
  • Object
show all
Defined in:
lib/Mailosaur/messages.rb

Overview

Operations for finding, retrieving, creating, forwarding, replying to, and deleting the email and SMS messages received by your Mailosaur inboxes (servers). Accessed via client.messages.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conn, handle_http_error) ⇒ Messages

Creates and initializes a new instance of the Messages class.

Parameters:

  • conn (Faraday::Connection)

    The client connection.

  • handle_http_error (Method)

    Callback used to convert HTTP error responses into errors.



12
13
14
15
# File 'lib/Mailosaur/messages.rb', line 12

def initialize(conn, handle_http_error)
  @conn = conn
  @handle_http_error = handle_http_error
end

Instance Attribute Details

#connConnection (readonly)

Returns the client connection.

Returns:

  • (Connection)

    the client connection.



18
19
20
# File 'lib/Mailosaur/messages.rb', line 18

def conn
  @conn
end

Instance Method Details

#create(server, message_create_options) ⇒ Mailosaur::Models::Message

Creates a new message that can be sent to a verified email address. This is useful in scenarios where you want an email to trigger a workflow in your product.

Parameters:

Returns:



196
197
198
199
200
201
# File 'lib/Mailosaur/messages.rb', line 196

def create(server, message_create_options)
  response = conn.post "api/messages?server=#{server}", message_create_options.to_json
  @handle_http_error.call(response) unless response.status == 200
  model = JSON.parse(response.body)
  Mailosaur::Models::Message.new(model)
end

#delete(id) ⇒ nil

Permanently deletes a message. Also deletes any attachments related to the message. This operation cannot be undone.

Parameters:

  • id (String)

    The identifier for the message.

Returns:

  • (nil)

    Once the message has been deleted.



71
72
73
74
75
# File 'lib/Mailosaur/messages.rb', line 71

def delete(id)
  response = conn.delete "api/messages/#{id}"
  @handle_http_error.call(response) unless response.status == 204
  nil
end

#delete_all(server) ⇒ nil

Permanently delete all messages within an inbox (server). This operation cannot be undone.

Parameters:

  • server (String)

    The unique identifier of the inbox (server).

Returns:

  • (nil)

    Once all messages within the inbox (server) have been deleted.



116
117
118
119
120
# File 'lib/Mailosaur/messages.rb', line 116

def delete_all(server)
  response = conn.delete "api/messages?server=#{server}"
  @handle_http_error.call(response) unless response.status == 204
  nil
end

#forward(id, message_forward_options) ⇒ Mailosaur::Models::Message

Forwards the specified message to a verified email address. This is useful for simulating a user forwarding one of your email messages.

Parameters:

Returns:



213
214
215
216
217
218
# File 'lib/Mailosaur/messages.rb', line 213

def forward(id, message_forward_options)
  response = conn.post "api/messages/#{id}/forward", message_forward_options.to_json
  @handle_http_error.call(response) unless response.status == 200
  model = JSON.parse(response.body)
  Mailosaur::Models::Message.new(model)
end

#generate_previews(id, options) ⇒ Mailosaur::Models::PreviewListResult

Generates screenshots of an email rendered in the specified email clients.

Parameters:

Returns:



246
247
248
249
250
251
# File 'lib/Mailosaur/messages.rb', line 246

def generate_previews(id, options)
  response = conn.post "api/messages/#{id}/screenshots", options.to_json
  @handle_http_error.call(response) unless response.status == 200
  model = JSON.parse(response.body)
  Mailosaur::Models::PreviewListResult.new(model)
end

#get(server, criteria, timeout: 10_000, received_after: DateTime.now - (1.0 / 24), dir: nil) ⇒ Mailosaur::Models::Message

Waits for a message to be found. Returns as soon as a message matching the specified search criteria is found. This is the most efficient method of looking up a message, therefore we recommend using it wherever possible.

Parameters:

  • server (String)

    The unique identifier of the containing inbox (server).

  • criteria (Mailosaur::Models::SearchCriteria)

    The criteria with which to find messages during a search.

  • timeout (Integer) (defaults to: 10_000)

    Specify how long to wait for a matching result (in milliseconds).

  • received_after (DateTime) (defaults to: DateTime.now - (1.0 / 24))

    Limits results to only messages received after this date/time.

  • dir (String) (defaults to: nil)

    Optionally limits results based on the direction (Sent or Received), with the default being Received.

Returns:

Raises:

  • (Mailosaur::MailosaurError)

    With error code no_messages_found if no matching message exists, or search_timeout if no matching message arrives before the timeout elapses.



40
41
42
43
44
45
46
# File 'lib/Mailosaur/messages.rb', line 40

def get(server, criteria, timeout: 10_000, received_after: DateTime.now - (1.0 / 24), dir: nil)
  # Defaults timeout to 10s, receivedAfter to 1h
  raise Mailosaur::MailosaurError.new('Must provide a valid Server ID.', 'invalid_request') if server.length != 8

  result = search(server, criteria, page: 0, items_per_page: 1, timeout: timeout, received_after: received_after, dir: dir)
  get_by_id(result.items[0].id)
end

#get_by_id(id) ⇒ Mailosaur::Models::Message

Retrieves the detail for a single message. Must be used in conjunction with either #list or #search in order to get the unique identifier for the required message.

Parameters:

  • id (String)

    The unique identifier of the message to be retrieved.

Returns:



56
57
58
59
60
61
# File 'lib/Mailosaur/messages.rb', line 56

def get_by_id(id)
  response = conn.get "api/messages/#{id}"
  @handle_http_error.call(response) unless response.status == 200
  model = JSON.parse(response.body)
  Mailosaur::Models::Message.new(model)
end

#list(server, page: nil, items_per_page: nil, received_after: nil, dir: nil) ⇒ Mailosaur::Models::MessageListResult

Returns a list of your messages in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first.

Parameters:

  • server (String)

    The unique identifier of the required inbox (server).

  • page (Integer) (defaults to: nil)

    Used in conjunction with items_per_page to support pagination.

  • items_per_page (Integer) (defaults to: nil)

    A limit on the number of results to be returned per page. Can be set between 1 and 1000 items, the default is 50.

  • received_after (DateTime) (defaults to: nil)

    Limits results to only messages received after this date/time.

  • dir (String) (defaults to: nil)

    Optionally limits results based on the direction (Sent or Received), with the default being Received.

Returns:



94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/Mailosaur/messages.rb', line 94

def list(server, page: nil, items_per_page: nil, received_after: nil, dir: nil)
  url = "api/messages?server=#{server}"
  url += page ? "&page=#{page}" : ''
  url += items_per_page ? "&itemsPerPage=#{items_per_page}" : ''
  url += received_after ? "&receivedAfter=#{CGI.escape(received_after.iso8601)}" : ''
  url += dir ? "&dir=#{dir}" : ''

  response = conn.get url

  @handle_http_error.call(response) unless response.status == 200

  model = JSON.parse(response.body)
  Mailosaur::Models::MessageListResult.new(model)
end

#reply(id, message_reply_options) ⇒ Mailosaur::Models::Message

Sends a reply to the specified message. This is useful for when simulating a user replying to one of your email or SMS messages.

Parameters:

Returns:



230
231
232
233
234
235
# File 'lib/Mailosaur/messages.rb', line 230

def reply(id, message_reply_options)
  response = conn.post "api/messages/#{id}/reply", message_reply_options.to_json
  @handle_http_error.call(response) unless response.status == 200
  model = JSON.parse(response.body)
  Mailosaur::Models::Message.new(model)
end

#search(server, criteria, page: nil, items_per_page: nil, timeout: nil, received_after: nil, error_on_timeout: true, dir: nil) ⇒ Mailosaur::Models::MessageListResult

Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

Parameters:

  • server (String)

    The unique identifier of the inbox (server) to search.

  • criteria (Mailosaur::Models::SearchCriteria)

    The criteria with which to find messages during a search.

  • page (Integer) (defaults to: nil)

    Used in conjunction with items_per_page to support pagination.

  • items_per_page (Integer) (defaults to: nil)

    A limit on the number of results to be returned per page. Can be set between 1 and 1000 items, the default is 50.

  • timeout (Integer) (defaults to: nil)

    Specify how long to wait for a matching result (in milliseconds).

  • received_after (DateTime) (defaults to: nil)

    Limits results to only messages received after this date/time.

  • error_on_timeout (Boolean) (defaults to: true)

    When set to false, an error will not be raised if the timeout is reached (default: true).

  • dir (String) (defaults to: nil)

    Optionally limits results based on the direction (Sent or Received), with the default being Received.

Returns:

Raises:

  • (Mailosaur::MailosaurError)

    With error code search_timeout if no matching message is found before the timeout elapses, unless error_on_timeout is set to false.



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/Mailosaur/messages.rb', line 148

def search(server, criteria, page: nil, items_per_page: nil, timeout: nil, received_after: nil, error_on_timeout: true, dir: nil)
  url = "api/messages/search?server=#{server}"
  url += page ? "&page=#{page}" : ''
  url += items_per_page ? "&itemsPerPage=#{items_per_page}" : ''
  url += received_after ? "&receivedAfter=#{CGI.escape(received_after.iso8601)}" : ''
  url += dir ? "&dir=#{dir}" : ''

  poll_count = 0
  start_time = Time.now.to_f

  loop do
    response = conn.post url, criteria.to_json

    @handle_http_error.call(response) unless response.status == 200

    model = JSON.parse(response.body)
    return Mailosaur::Models::MessageListResult.new(model) if timeout.to_i.zero? || !model['items'].empty?

    delay_pattern = (response.headers['x-ms-delay'] || '1000').split(',').map(&:to_i)

    delay = poll_count >= delay_pattern.length ? delay_pattern[delay_pattern.length - 1] : delay_pattern[poll_count]

    poll_count += 1

    ## Stop if timeout will be exceeded
    if ((1000 * (Time.now.to_f - start_time).to_i) + delay) > timeout
      return Mailosaur::Models::MessageListResult.new(model) unless error_on_timeout

      msg = format('No matching messages found in time. By default, only messages received in the last hour are checked (use receivedAfter to override this). The search criteria used for this query was [%s] which timed out after %sms',
                   criteria.to_json, timeout)
      raise Mailosaur::MailosaurError.new(msg, 'search_timeout')
    end

    sleep(delay / 1000)
  end
end