sendio 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +31 -0
  3. data/LICENSE +22 -0
  4. data/NOTICE +1 -0
  5. data/README.md +210 -0
  6. data/app/controllers/action_mailbox/ingresses/sendio/inbound_emails_controller.rb +95 -0
  7. data/lib/sendio/action_mailbox/engine.rb +19 -0
  8. data/lib/sendio/action_mailbox/message_builder.rb +162 -0
  9. data/lib/sendio/action_mailbox.rb +5 -0
  10. data/lib/sendio/api_keys.rb +32 -0
  11. data/lib/sendio/automations/runs.rb +22 -0
  12. data/lib/sendio/automations/templates.rb +29 -0
  13. data/lib/sendio/automations.rb +64 -0
  14. data/lib/sendio/batch.rb +36 -0
  15. data/lib/sendio/broadcasts.rb +180 -0
  16. data/lib/sendio/client.rb +19 -0
  17. data/lib/sendio/contact_properties.rb +106 -0
  18. data/lib/sendio/contacts/imports.rb +64 -0
  19. data/lib/sendio/contacts/segments.rb +66 -0
  20. data/lib/sendio/contacts/topics.rb +80 -0
  21. data/lib/sendio/contacts.rb +131 -0
  22. data/lib/sendio/domains.rb +60 -0
  23. data/lib/sendio/emails/attachments.rb +67 -0
  24. data/lib/sendio/emails/receiving/attachments.rb +69 -0
  25. data/lib/sendio/emails/receiving.rb +51 -0
  26. data/lib/sendio/emails.rb +124 -0
  27. data/lib/sendio/errors.rb +59 -0
  28. data/lib/sendio/events.rb +46 -0
  29. data/lib/sendio/logs.rb +20 -0
  30. data/lib/sendio/mailboxes.rb +87 -0
  31. data/lib/sendio/mailer.rb +241 -0
  32. data/lib/sendio/multipart_request.rb +67 -0
  33. data/lib/sendio/oauth_grants.rb +20 -0
  34. data/lib/sendio/pagination_helper.rb +30 -0
  35. data/lib/sendio/railtie.rb +14 -0
  36. data/lib/sendio/request.rb +122 -0
  37. data/lib/sendio/response.rb +154 -0
  38. data/lib/sendio/segments.rb +38 -0
  39. data/lib/sendio/suppressions/batch.rb +44 -0
  40. data/lib/sendio/suppressions.rb +64 -0
  41. data/lib/sendio/templates.rb +50 -0
  42. data/lib/sendio/topics.rb +38 -0
  43. data/lib/sendio/usage.rb +14 -0
  44. data/lib/sendio/version.rb +5 -0
  45. data/lib/sendio/webhooks.rb +329 -0
  46. data/lib/sendio.rb +78 -0
  47. metadata +119 -0
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendio
4
+ # The Mailboxes module manages mailboxes: real email accounts with an IMAP/SMTP login.
5
+ #
6
+ # @example Create a mailbox on a verified domain
7
+ # mailbox = Sendio::Mailboxes.create(address: "support@yourdomain.com")
8
+ # mailbox[:credentials] # shown once, when IMAP/SMTP is ready
9
+ #
10
+ # @example List mailboxes
11
+ # Sendio::Mailboxes.list
12
+ #
13
+ # @example Turn warmup off
14
+ # Sendio::Mailboxes.update(mailbox_id: "mbx_123", warmup_enabled: false)
15
+ #
16
+ # @example Reset the IMAP/SMTP password
17
+ # Sendio::Mailboxes.reset_password("mbx_123")
18
+ #
19
+ # @example Delete a mailbox
20
+ # Sendio::Mailboxes.remove("mbx_123")
21
+ module Mailboxes
22
+ class << self
23
+ # Create a mailbox
24
+ #
25
+ # The domain must be verified. Raises Sendio::Error (409) if the address already exists.
26
+ #
27
+ # @param params [Hash] The mailbox parameters
28
+ # @option params [String] :address The full address, e.g. "support@yourdomain.com"
29
+ # @option params [String] :local_part The part before the "@" (with :domain_id, instead of :address)
30
+ # @option params [String] :domain_id The domain ID (with :local_part)
31
+ # @option params [String] :username For a free mailbox (no domain): the username
32
+ # @option params [String] :org For a free mailbox: the organization (optional)
33
+ # @option params [String] :display_name For a free mailbox: the display name (optional)
34
+ #
35
+ # @return [Hash] The mailbox object, plus :credentials (shown once) when IMAP/SMTP is ready.
36
+ # The password is also an API key for that mailbox; store it safely.
37
+ def create(params = {})
38
+ path = "mailboxes"
39
+ Sendio::Request.new(path, params, "post").perform
40
+ end
41
+
42
+ # List all mailboxes (not paginated)
43
+ #
44
+ # @return [Hash] A list object whose :data holds the mailbox objects
45
+ def list
46
+ path = "mailboxes"
47
+ Sendio::Request.new(path, {}, "get").perform
48
+ end
49
+
50
+ # Update a mailbox
51
+ #
52
+ # @param params [Hash] The mailbox update parameters
53
+ # @option params [String] :mailbox_id The mailbox ID (required)
54
+ # @option params [Boolean] :warmup_enabled Whether warmup is on (required)
55
+ #
56
+ # @return [Hash] The updated mailbox object
57
+ def update(params = {})
58
+ path = "mailboxes/#{params[:mailbox_id]}"
59
+ Sendio::Request.new(path, { warmup_enabled: params[:warmup_enabled] }, "patch").perform
60
+ end
61
+
62
+ # Reset the IMAP/SMTP password of a mailbox
63
+ #
64
+ # The old password stops working. The new password is also an API key for that mailbox.
65
+ #
66
+ # @param mailbox_id [String] The mailbox ID
67
+ #
68
+ # @return [Hash] A mailbox_credentials object with :id, :address, :credentials and :note
69
+ def reset_password(mailbox_id = "")
70
+ path = "mailboxes/#{mailbox_id}/password"
71
+ Sendio::Request.new(path, {}, "post").perform
72
+ end
73
+
74
+ # Delete a mailbox
75
+ #
76
+ # Removes the email account, and the agent inbox on it if there is one.
77
+ #
78
+ # @param mailbox_id [String] The mailbox ID
79
+ #
80
+ # @return [Hash] Confirmation object with :object, :id and :deleted
81
+ def remove(mailbox_id = "")
82
+ path = "mailboxes/#{mailbox_id}"
83
+ Sendio::Request.new(path, {}, "delete").perform
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,241 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sendio"
4
+
5
+ module Sendio
6
+ # Mailer class used by railtie
7
+ class Mailer
8
+ attr_accessor :config, :settings
9
+
10
+ # These are set as `headers` by the Rails API, but these will be filtered out
11
+ # when constructing the send.io API payload, since they're are sent as post params.
12
+ # https://developer.send.io/docs/api
13
+ IGNORED_HEADERS = %w[
14
+ cc bcc
15
+ from reply-to to subject mime-version
16
+ html text
17
+ content-type content-transfer-encoding tags scheduled_at
18
+ headers options
19
+ ].freeze
20
+
21
+ SUPPORTED_OPTIONS = %w[idempotency_key].freeze
22
+
23
+ def initialize(config)
24
+ @config = config
25
+ raise Sendio::Error.new("Make sure your API Key is set", @config) unless Sendio.api_key
26
+
27
+ # avoids NilError exception
28
+ @settings = { return_response: true }
29
+ end
30
+
31
+ #
32
+ # Overwritten deliver! method
33
+ #
34
+ # @param Mail mail
35
+ #
36
+ # @return Object sendio response
37
+ #
38
+ def deliver!(mail)
39
+ params = build_sendio_params(mail)
40
+ options = get_options(mail) if mail[:options].present?
41
+ resp = Sendio::Emails.send(params, options: options || {})
42
+ mail.message_id = resp[:id] if resp[:error].nil?
43
+ resp
44
+ end
45
+
46
+ #
47
+ # Builds the payload for sending
48
+ #
49
+ # @param Mail mail rails mail object
50
+ #
51
+ # @return Hash hash with all Sendio params
52
+ #
53
+ def build_sendio_params(mail)
54
+ params = {
55
+ from: get_from(mail),
56
+ to: mail.to,
57
+ subject: mail.subject
58
+ }
59
+ params.merge!(get_addons(mail))
60
+ params.merge!(get_headers(mail))
61
+ params.merge!(get_tags(mail))
62
+ params[:attachments] = get_attachments(mail) if mail.attachments.present?
63
+ params.merge!(get_contents(mail))
64
+ params
65
+ end
66
+
67
+ #
68
+ # Add custom headers fields.
69
+ #
70
+ # Both ways are supported:
71
+ #
72
+ # 1. Through the `#mail()` method ie:
73
+ # mail(headers: { "X-Custom-Header" => "value" })
74
+ #
75
+ # 2. Through the Rails `#headers` method ie:
76
+ # headers["X-Custom-Header"] = "value"
77
+ #
78
+ #
79
+ # setting the header values through the `#mail` method will overwrite values set
80
+ # through the `#headers` method using the same key.
81
+ #
82
+ # @param Mail mail Rails Mail object
83
+ #
84
+ # @return Hash hash with headers param
85
+ #
86
+ def get_headers(mail)
87
+ params = {}
88
+
89
+ if mail[:headers].present? || unignored_headers(mail).present?
90
+ params[:headers] = {}
91
+ params[:headers].merge!(headers_values(mail)) if unignored_headers(mail).present?
92
+ params[:headers].merge!(mail_headers_values(mail)) if mail[:headers].present?
93
+ end
94
+
95
+ params
96
+ end
97
+
98
+ #
99
+ # Adds additional options fields.
100
+ # Currently supports only :idempotency_key
101
+ #
102
+ # @param Mail mail Rails Mail object
103
+ # @return Hash hash with headers param
104
+ #
105
+ def get_options(mail)
106
+ opts = {}
107
+ if mail[:options].present?
108
+ opts.merge!(mail[:options].unparsed_value)
109
+ opts.delete_if { |k, _v| !SUPPORTED_OPTIONS.include?(k.to_s) }
110
+ end
111
+ opts
112
+ end
113
+
114
+ # Remove nils from header values
115
+ def cleanup_headers(headers)
116
+ headers.delete_if { |_k, v| v.nil? }
117
+ end
118
+
119
+ # Gets the values of the headers that are set through the `#mail` method
120
+ #
121
+ # @param Mail mail Rails Mail object
122
+ # @return Hash hash with mail headers values
123
+ def mail_headers_values(mail)
124
+ params = {}
125
+ mail[:headers].unparsed_value.each do |k, v|
126
+ params[k.to_s] = v
127
+ end
128
+ cleanup_headers(params)
129
+ params
130
+ end
131
+
132
+ # Gets the values of the headers that are set through the `#headers` method
133
+ #
134
+ # @param Mail mail Rails Mail object
135
+ # @return Hash hash with headers values
136
+ def headers_values(mail)
137
+ params = {}
138
+ unignored_headers(mail).each do |h|
139
+ params[h.name.to_s] = h.unparsed_value
140
+ end
141
+ cleanup_headers(params)
142
+ params
143
+ end
144
+
145
+ #
146
+ # Add tags fields
147
+ #
148
+ # @param Mail mail Rails Mail object
149
+ #
150
+ # @return Hash hash with tags param
151
+ #
152
+ def get_tags(mail)
153
+ params = {}
154
+ params[:tags] = mail[:tags].unparsed_value if mail[:tags].present?
155
+ params
156
+ end
157
+
158
+ #
159
+ # Add cc, bcc, reply_to fields
160
+ #
161
+ # @param Mail mail Rails Mail Object
162
+ #
163
+ # @return Hash hash containing cc/bcc/reply_to attrs
164
+ #
165
+ def get_addons(mail)
166
+ params = {}
167
+ params[:cc] = mail.cc if mail.cc.present?
168
+ params[:bcc] = mail.bcc if mail.bcc.present?
169
+ params[:reply_to] = mail.reply_to if mail.reply_to.present?
170
+ params
171
+ end
172
+
173
+ #
174
+ # Gets the body of the email
175
+ #
176
+ # @param Mail mail Rails Mail Object
177
+ #
178
+ # @return Hash hash containing html/text or both attrs
179
+ #
180
+ def get_contents(mail)
181
+ params = {}
182
+ case mail.mime_type
183
+ when "text/plain"
184
+ params[:text] = mail.body.decoded
185
+ when "text/html"
186
+ params[:html] = mail.body.decoded
187
+ when "multipart/alternative", "multipart/mixed", "multipart/related"
188
+ params[:text] = mail.text_part.decoded if mail.text_part
189
+ params[:html] = mail.html_part.decoded if mail.html_part
190
+ end
191
+ params
192
+ end
193
+
194
+ #
195
+ # Properly gets the `from` attr
196
+ #
197
+ # @param Mail input object
198
+ #
199
+ # @return String `from` string
200
+ #
201
+ def get_from(input)
202
+ return input.from.first if input[:from].nil?
203
+
204
+ from = input[:from].formatted
205
+ return from.first if from.is_a? Array
206
+
207
+ from.to_s
208
+ end
209
+
210
+ #
211
+ # Handle attachments when present
212
+ #
213
+ # @return Array attachments array
214
+ #
215
+ def get_attachments(mail)
216
+ attachments = []
217
+ mail.attachments.each do |part|
218
+ attachment = {
219
+ filename: part.filename,
220
+ content: part.body.decoded.bytes
221
+ }
222
+
223
+ # Rails uses the auto generated cid for inline attachments
224
+ attachment[:content_id] = part.cid if part.inline?
225
+ attachments.append(attachment)
226
+ end
227
+ attachments
228
+ end
229
+
230
+ #
231
+ # Get all headers that are not ignored
232
+ #
233
+ # @param Mail mail
234
+ #
235
+ # @return Array headers
236
+ #
237
+ def unignored_headers(mail)
238
+ @unignored_headers ||= mail.header_fields.reject { |h| IGNORED_HEADERS.include?(h.name.downcase) }
239
+ end
240
+ end
241
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Sendio
6
+ # Handles multipart/form-data requests (file uploads).
7
+ # Builds the multipart body directly instead of relying on HTTParty's
8
+ # duck-typing file detection, which requires a :path method.
9
+ class MultipartRequest < Request
10
+ NEWLINE = "\r\n"
11
+ private_constant :NEWLINE
12
+
13
+ private
14
+
15
+ def build_request_options
16
+ boundary = SecureRandom.hex(16)
17
+ headers = @headers.merge("Content-Type" => "multipart/form-data; boundary=#{boundary}")
18
+ { headers: headers, body: build_multipart_body(boundary) }
19
+ end
20
+
21
+ def build_multipart_body(boundary)
22
+ body = "".b
23
+
24
+ body << part(boundary, "file", read_file(@body[:file]), filename: "import.csv", content_type: "text/csv")
25
+ optional_fields.each { |name, value| body << part(boundary, name, value) }
26
+ body << "--#{boundary}--#{NEWLINE}".b
27
+
28
+ body
29
+ end
30
+
31
+ def part(boundary, name, value, filename: nil, content_type: nil)
32
+ disposition = %(Content-Disposition: form-data; name="#{name}")
33
+ disposition += %(; filename="#{filename}") if filename
34
+
35
+ header = "--#{boundary}#{NEWLINE}#{disposition}#{NEWLINE}"
36
+ header += "Content-Type: #{content_type}#{NEWLINE}" if content_type
37
+ header += NEWLINE
38
+
39
+ header.b + value.to_s.b + NEWLINE.b
40
+ end
41
+
42
+ def read_file(file_data)
43
+ if file_data.respond_to?(:read)
44
+ content = file_data.read
45
+ file_data.rewind if file_data.respond_to?(:rewind)
46
+ content.b
47
+ else
48
+ file_data.to_s.b
49
+ end
50
+ end
51
+
52
+ def optional_fields
53
+ {
54
+ column_map: @body[:column_map] && serialize_json(@body[:column_map]),
55
+ on_conflict: @body[:on_conflict],
56
+ segments: @body[:segments] && serialize_json(@body[:segments]),
57
+ topics: @body[:topics] && serialize_json(@body[:topics])
58
+ }.compact
59
+ end
60
+
61
+ def serialize_json(value)
62
+ return value if value.is_a?(String)
63
+
64
+ value.to_json
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendio
4
+ # oauth grants api wrapper
5
+ module OAuthGrants
6
+ class << self
7
+ # https://developer.send.io/docs/api
8
+ def list(params = {})
9
+ path = Sendio::PaginationHelper.build_paginated_path("oauth/grants", params)
10
+ Sendio::Request.new(path, {}, "get").perform
11
+ end
12
+
13
+ # https://developer.send.io/docs/api
14
+ def revoke(oauth_grant_id = "")
15
+ path = "oauth/grants/#{oauth_grant_id}"
16
+ Sendio::Request.new(path, {}, "delete").perform
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendio
4
+ # Helper class for building paginated query strings
5
+ class PaginationHelper
6
+ class << self
7
+ # Builds a paginated path with query parameters
8
+ #
9
+ # @param base_path [String] the base API path
10
+ # @param query_params [Hash] optional pagination parameters
11
+ # @option query_params [Integer] :limit Number of items to retrieve (max 100)
12
+ # @option query_params [String] :after ID after which to retrieve more items
13
+ # @option query_params [String] :before ID before which to retrieve more items
14
+ # @return [String] the path with query parameters
15
+ def build_paginated_path(base_path, query_params = nil)
16
+ return base_path if query_params.nil? || query_params.empty?
17
+
18
+ # Filter out nil values and convert to string keys
19
+ filtered_params = query_params.compact.transform_keys(&:to_s)
20
+
21
+ # Build query string
22
+ query_string = filtered_params.map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }.join("&")
23
+
24
+ return base_path if query_string.empty?
25
+
26
+ "#{base_path}?#{query_string}"
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sendio"
4
+ require "sendio/mailer"
5
+
6
+ module Sendio
7
+ # Main railtime class
8
+ class Railtie < ::Rails::Railtie
9
+ ActiveSupport.on_load(:action_mailer) do
10
+ add_delivery_method :sendio, Sendio::Mailer
11
+ ActiveSupport.run_load_hooks(:sendio_mailer, Sendio::Mailer)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendio
4
+ # This class is responsible for making the appropriate HTTP calls
5
+ # and raising the specific errors based on the response.
6
+ class Request
7
+ # Base URL resolved when the gem is loaded (always ends with "/").
8
+ # Kept for backwards compatibility; requests use Sendio.base_url, which
9
+ # also honours runtime changes (Sendio.base_url = "...").
10
+ env_base_url = ENV.fetch("SENDIO_BASE_URL", "").strip
11
+ BASE_URL = "#{(env_base_url.empty? ? "https://api.send.io" : env_base_url).sub(%r{/+\z}, "")}/".freeze
12
+
13
+ attr_accessor :body, :verb, :options
14
+
15
+ def initialize(path = "", body = {}, verb = "POST", options: {})
16
+ raise if (api_key = Sendio.api_key).nil?
17
+
18
+ api_key = api_key.call if api_key.is_a?(Proc)
19
+
20
+ @path = path
21
+ @body = body
22
+ @verb = verb
23
+ @options = options
24
+ @headers = {
25
+ "Content-Type" => "application/json",
26
+ "Accept" => "application/json",
27
+ "User-Agent" => "sendio-ruby:#{Sendio::VERSION}",
28
+ "Authorization" => "Bearer #{api_key}"
29
+ }
30
+
31
+ set_idempotency_key
32
+ set_batch_validation
33
+ end
34
+
35
+ # Performs the HTTP call
36
+ def perform
37
+ options = build_request_options
38
+ resp = HTTParty.send(@verb.to_sym, "#{Sendio.base_url}#{@path}", options)
39
+
40
+ check_json!(resp)
41
+ data = process_response(resp)
42
+ headers = extract_headers(resp)
43
+
44
+ Sendio::Response.new(data, headers)
45
+ end
46
+
47
+ def handle_error!(data, resp = nil)
48
+ code = data[:statusCode]
49
+ body = data[:message]
50
+ headers = resp.respond_to?(:headers) ? resp.headers : (data[:headers] || {})
51
+
52
+ # get error from the known list of errors
53
+ error_class = Sendio::Error::ERRORS[code] || Sendio::Error
54
+ raise error_class.new(body, code, headers)
55
+ end
56
+
57
+ private
58
+
59
+ def build_request_options
60
+ options = { headers: @headers }
61
+
62
+ if get_request_with_query?
63
+ options[:query] = @body
64
+ elsif !@body.empty?
65
+ options[:body] = @body.to_json
66
+ end
67
+
68
+ options
69
+ end
70
+
71
+ def get_request_with_query?
72
+ @verb.downcase == "get" && !@body.empty?
73
+ end
74
+
75
+ def process_response(resp)
76
+ # Extract the parsed data from HTTParty response or use the hash directly (for tests/mocks)
77
+ data = resp.respond_to?(:parsed_response) ? resp.parsed_response : resp
78
+ data ||= {}
79
+ data.transform_keys!(&:to_sym) unless resp.body.empty?
80
+ handle_error!(data, resp) if error_response?(data)
81
+ data
82
+ end
83
+
84
+ def error_response?(resp)
85
+ resp[:statusCode] && resp[:statusCode] != 200 && resp[:statusCode] != 201
86
+ end
87
+
88
+ def set_idempotency_key
89
+ # Only set idempotency key if the verb is POST for now.
90
+ #
91
+ # Does not set it if the idempotency_key is nil or empty
92
+ if @verb.downcase == "post" && !@options[:idempotency_key].nil? && !@options[:idempotency_key].empty?
93
+ @headers["Idempotency-Key"] = @options[:idempotency_key]
94
+ end
95
+ end
96
+
97
+ def set_batch_validation
98
+ # Set x-batch-validation header for batch emails
99
+ # Supported values: 'strict' (default) or 'permissive'
100
+ if @path == "emails/batch" && @options[:batch_validation]
101
+ @headers["x-batch-validation"] = @options[:batch_validation]
102
+ end
103
+ end
104
+
105
+ def check_json!(resp)
106
+ if resp.body.is_a?(Hash)
107
+ JSON.parse(resp.body.to_json)
108
+ else
109
+ JSON.parse(resp.body)
110
+ end
111
+ rescue JSON::ParserError, TypeError
112
+ raise Sendio::Error::InternalServerError.new("send.io API returned an unexpected response", nil)
113
+ end
114
+
115
+ # Extract and normalize headers from the HTTParty response
116
+ def extract_headers(resp)
117
+ return {} unless resp.respond_to?(:headers)
118
+
119
+ resp.headers.to_h.transform_keys { |k| k.to_s.downcase }
120
+ end
121
+ end
122
+ end