bmailu 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f0787857f7910f26db031ff5be5f4dc8bcdf6168f4100961fa9f1273e6e9db41
4
+ data.tar.gz: 21f6732b5b3e1ae7962d768984a84f59d833308807d322f502bded28f9460e91
5
+ SHA512:
6
+ metadata.gz: c73e8db7e42ae4ab16ee72927ca3b1117b2b553efdb040d6e026eb0049c833c21499d10eb48095f1f3b8e8ab9f83b921a609a922ecae5d65ac405eb7f5de0ae9
7
+ data.tar.gz: 12fd5621957a601466229bdfabcbf544b34414f28dad17827fcd223294e4c82b76cb5291461edcdcec09d2ef40d7033182889a84a9f105caa600a725869118eb
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Khiyan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # Bmailu for Ruby
2
+
3
+ The official Ruby SDK for the Bmailu Email API. It needs Ruby 2.7 or newer and uses only the standard library
4
+ (net/http and json).
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ gem install bmailu
10
+ ```
11
+
12
+ ## Send an email
13
+
14
+ ```ruby
15
+ require "bmailu"
16
+ bmailu = Bmailu::Client.new("bmk_...") # or set BMAILU_API_KEY
17
+ bmailu.emails.send({ from: "Shop <hello@shop.com>", to: "ann@example.com", subject: "Hello", html: "<p>Hello!</p>" })
18
+ ```
19
+
20
+ You pass hashes and get hashes back (string keys). The answer to a send is `{"id" => "..."}`.
21
+ Keep the braces around the message: `send` also takes the `idempotency_key:` keyword.
22
+
23
+ To send safely twice (for example after a timeout), add an idempotency key. The second call returns the same id:
24
+
25
+ ```ruby
26
+ bmailu.emails.send(message, idempotency_key: "order-1234")
27
+ ```
28
+
29
+ ## What is covered
30
+
31
+ The brief for 0.1.0 asks for emails, events, contacts, broadcasts, templates and webhooks plus a generic call.
32
+ This gem goes further: every operation of the API has a method, with the same names as the Python SDK:
33
+ `emails` (send, batch, get, list, export, update / reschedule, cancel), `events`, `contacts`, `segments`, `topics`,
34
+ `broadcasts` (send, cancel, test, stats), `templates` (publish, versions, render, preview), `webhooks`
35
+ (deliveries, replay_delivery, rotate_secret), `suppressions`, `automations` (start, stop, runs), `metrics`, `logs`,
36
+ `domains`, `mailboxes`, `aliases`, `sending_domains`, `api_keys`, `me` and `inbox`.
37
+
38
+ `api_keys` and `sending_domains` are in the spec but need a panel session: an API key gets the error `session_only`.
39
+
40
+ For anything else there is a generic call:
41
+
42
+ ```ruby
43
+ bmailu.request("GET", "/emails", query: { status: "bounced", limit: 10 })
44
+ ```
45
+
46
+ ## Errors
47
+
48
+ A failed call raises `Bmailu::Error` with `status` (HTTP status), `code` and `error_message`:
49
+
50
+ ```ruby
51
+ begin
52
+ bmailu.emails.send({ ... })
53
+ rescue Bmailu::Error => e
54
+ puts e.status, e.code, e.error_message # 403 domain_not_verified ...
55
+ end
56
+ ```
57
+
58
+ ## Verify a webhook
59
+
60
+ Pass the raw body, the request headers and the endpoint's signing secret. You get the parsed event back,
61
+ or a `Bmailu::WebhookVerificationError` if the signature is wrong or the timestamp is more than 5 minutes away.
62
+ Rack-style headers (`HTTP_WEBHOOK_ID`) work too.
63
+
64
+ ```ruby
65
+ event = Bmailu::Webhook.verify(request.raw_post, request.headers.to_h, "whsec_...")
66
+ puts event["type"]
67
+ ```
68
+
69
+ ## Settings
70
+
71
+ - `Bmailu::Client.new(api_key = nil, base_url: nil, timeout: 30)`
72
+ - `BMAILU_API_KEY` and `BMAILU_BASE_URL` are read from the environment when you leave them out.
73
+
74
+ ## Tests
75
+
76
+ `./test.sh` starts a local Bmailu API (`../test-server.js`, needs Node) and runs the minitest suite.
77
+ Nothing is really sent.
78
+
79
+ Docs: https://bmailu.com/docs/
80
+
81
+ License: MIT
data/bmailu.gemspec ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/bmailu/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "bmailu"
7
+ s.version = Bmailu::VERSION
8
+ s.summary = "Official Ruby SDK for the Bmailu Email API"
9
+ s.description = "Send email, manage contacts, broadcasts, templates and webhooks with the Bmailu API. Standard library only."
10
+ s.authors = ["Bmailu"]
11
+ s.homepage = "https://bmailu.com/"
12
+ s.license = "MIT"
13
+ s.required_ruby_version = ">= 2.7"
14
+ s.files = Dir["lib/**/*.rb"] + %w[README.md LICENSE bmailu.gemspec]
15
+ s.require_paths = ["lib"]
16
+ s.metadata = { "documentation_uri" => "https://bmailu.com/docs/", "homepage_uri" => "https://bmailu.com/",
17
+ "source_code_uri" => "https://github.com/khiyandev/bmailu-sdks/tree/main/ruby", "bug_tracker_uri" => "https://github.com/khiyandev/bmailu-sdks/issues",
18
+ "rubygems_mfa_required" => "true" }
19
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bmailu
4
+ # An error answer from the API (or a network failure, status 0).
5
+ class Error < StandardError
6
+ attr_reader :status, :code, :body
7
+
8
+ def initialize(status, code, message, body = nil)
9
+ super("#{code}: #{message} (HTTP #{status})")
10
+ @status = status
11
+ @code = code
12
+ @error_message = message
13
+ @body = body
14
+ end
15
+
16
+ # The plain-words message from the API.
17
+ def error_message
18
+ @error_message
19
+ end
20
+ end
21
+
22
+ # The webhook signature or timestamp is not valid.
23
+ class WebhookVerificationError < StandardError; end
24
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+
5
+ module Bmailu
6
+ module Resources
7
+ # Base of every resource: holds the client and builds paths.
8
+ class Resource
9
+ def initialize(client)
10
+ @client = client
11
+ end
12
+
13
+ private
14
+
15
+ # One URL path segment, fully encoded.
16
+ def seg(value)
17
+ ERB::Util.url_encode(value.to_s)
18
+ end
19
+
20
+ def idem(key)
21
+ key.nil? || key.to_s.empty? ? {} : { "Idempotency-Key" => key.to_s }
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,599 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Generated from the Bmailu OpenAPI operation list. One method per operation.
4
+ module Bmailu
5
+ module Resources
6
+ class Me < Resource
7
+ # Who the key belongs to. GET /me
8
+ def get
9
+ @client.request("GET", "/me")
10
+ end
11
+
12
+ # Set the recovery email. PATCH /me
13
+ def update(params)
14
+ @client.request("PATCH", "/me", body: params)
15
+ end
16
+ end
17
+
18
+ class Domains < Resource
19
+ # List mailbox domains. GET /domains
20
+ def list
21
+ @client.request("GET", "/domains")
22
+ end
23
+
24
+ # Add a mailbox domain. POST /domains
25
+ def create(params)
26
+ @client.request("POST", "/domains", body: params)
27
+ end
28
+
29
+ # Get a domain with DNS records, mailboxes and aliases. GET /domains/{domain_id}
30
+ def get(domain_id)
31
+ @client.request("GET", "/domains/#{seg(domain_id)}")
32
+ end
33
+
34
+ # Remove a pending domain. DELETE /domains/{domain_id}
35
+ def delete(domain_id)
36
+ @client.request("DELETE", "/domains/#{seg(domain_id)}")
37
+ end
38
+
39
+ # Check the ownership TXT record. POST /domains/{domain_id}/verify
40
+ def verify(domain_id)
41
+ @client.request("POST", "/domains/#{seg(domain_id)}/verify")
42
+ end
43
+
44
+ # Check MX, SPF, DKIM and DMARC. POST /domains/{domain_id}/dns-check
45
+ def check_dns(domain_id)
46
+ @client.request("POST", "/domains/#{seg(domain_id)}/dns-check")
47
+ end
48
+
49
+ # Catch-all on (mailbox id) or off (null). PUT /domains/{domain_id}/catch-all
50
+ def set_catch_all(domain_id, mailbox_id)
51
+ @client.request("PUT", "/domains/#{seg(domain_id)}/catch-all", body: { mailbox_id: mailbox_id })
52
+ end
53
+ end
54
+
55
+ class Mailboxes < Resource
56
+ # Create a mailbox (password shown once). POST /domains/{domain_id}/mailboxes
57
+ def create(domain_id, params)
58
+ @client.request("POST", "/domains/#{seg(domain_id)}/mailboxes", body: params)
59
+ end
60
+
61
+ # Delete a mailbox (restorable for 14 days). DELETE /mailboxes/{mailbox_id}
62
+ def delete(mailbox_id)
63
+ @client.request("DELETE", "/mailboxes/#{seg(mailbox_id)}")
64
+ end
65
+
66
+ # Restore a deleted mailbox. POST /mailboxes/{mailbox_id}/restore
67
+ def restore(mailbox_id)
68
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/restore")
69
+ end
70
+
71
+ # Set a new random password. POST /mailboxes/{mailbox_id}/password
72
+ def reset_password(mailbox_id)
73
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/password")
74
+ end
75
+
76
+ # Forward copies (or stop with null). PUT /mailboxes/{mailbox_id}/forward
77
+ def set_forward(mailbox_id, to)
78
+ @client.request("PUT", "/mailboxes/#{seg(mailbox_id)}/forward", body: { to: to })
79
+ end
80
+
81
+ # Send a test email to the mailbox. POST /mailboxes/{mailbox_id}/test-email
82
+ def send_test_email(mailbox_id)
83
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/test-email")
84
+ end
85
+ end
86
+
87
+ class Aliases < Resource
88
+ # Add an alias. POST /domains/{domain_id}/aliases
89
+ def create(domain_id, params)
90
+ @client.request("POST", "/domains/#{seg(domain_id)}/aliases", body: params)
91
+ end
92
+
93
+ # Remove an alias. DELETE /aliases/{alias_id}
94
+ def delete(alias_id)
95
+ @client.request("DELETE", "/aliases/#{seg(alias_id)}")
96
+ end
97
+ end
98
+
99
+ class ApiKeys < Resource
100
+ # List API keys. GET /api-keys
101
+ def list
102
+ @client.request("GET", "/api-keys")
103
+ end
104
+
105
+ # Create an API key (shown once). POST /api-keys
106
+ def create(params)
107
+ @client.request("POST", "/api-keys", body: params)
108
+ end
109
+
110
+ # Revoke an API key. DELETE /api-keys/{key_id}
111
+ def revoke(key_id)
112
+ @client.request("DELETE", "/api-keys/#{seg(key_id)}")
113
+ end
114
+ end
115
+
116
+ class SendingDomains < Resource
117
+ # List sending domains. GET /sending-domains
118
+ def list
119
+ @client.request("GET", "/sending-domains")
120
+ end
121
+
122
+ # Add a sending domain. POST /sending-domains
123
+ def create(params)
124
+ @client.request("POST", "/sending-domains", body: params)
125
+ end
126
+
127
+ # Get a sending domain. GET /sending-domains/{sending_domain_id}
128
+ def get(sending_domain_id)
129
+ @client.request("GET", "/sending-domains/#{seg(sending_domain_id)}")
130
+ end
131
+
132
+ # Remove a sending domain. DELETE /sending-domains/{sending_domain_id}
133
+ def delete(sending_domain_id)
134
+ @client.request("DELETE", "/sending-domains/#{seg(sending_domain_id)}")
135
+ end
136
+
137
+ # Check the TXT and create DKIM keys. POST /sending-domains/{sending_domain_id}/verify
138
+ def verify(sending_domain_id)
139
+ @client.request("POST", "/sending-domains/#{seg(sending_domain_id)}/verify")
140
+ end
141
+
142
+ # Check DKIM, bounce MX and SPF. POST /sending-domains/{sending_domain_id}/check
143
+ def check(sending_domain_id)
144
+ @client.request("POST", "/sending-domains/#{seg(sending_domain_id)}/check")
145
+ end
146
+
147
+ # Change settings, e.g. { tls: "enforced" }. PATCH /sending-domains/{sending_domain_id}
148
+ def update(sending_domain_id, params)
149
+ @client.request("PATCH", "/sending-domains/#{seg(sending_domain_id)}", body: params)
150
+ end
151
+
152
+ # Deliverability insights. GET /sending-domains/{sending_domain_id}/insights
153
+ def insights(sending_domain_id)
154
+ @client.request("GET", "/sending-domains/#{seg(sending_domain_id)}/insights")
155
+ end
156
+ end
157
+
158
+ class Emails < Resource
159
+ # Send an email. Returns {id}. POST /emails
160
+ def send(params, idempotency_key: nil)
161
+ @client.request("POST", "/emails", body: params, headers: idem(idempotency_key))
162
+ end
163
+
164
+ # Send up to 100 emails. Returns {data: [{id}]}. POST /emails/batch
165
+ def batch(emails, idempotency_key: nil)
166
+ @client.request("POST", "/emails/batch", body: emails, headers: idem(idempotency_key))
167
+ end
168
+
169
+ # Get an email with per-recipient status and events. GET /emails/{email_id}
170
+ def get(email_id)
171
+ @client.request("GET", "/emails/#{seg(email_id)}")
172
+ end
173
+
174
+ # query: limit, before, status, source, key, domain, q, days. GET /emails
175
+ def list(query = {})
176
+ @client.request("GET", "/emails", body: nil, query: query)
177
+ end
178
+
179
+ # CSV text of the filtered list. GET /emails/export
180
+ def export(query = {})
181
+ @client.request("GET", "/emails/export", body: nil, query: query)
182
+ end
183
+
184
+ # Reschedule: {scheduled_at}. PATCH /emails/{email_id}
185
+ def update(email_id, params)
186
+ @client.request("PATCH", "/emails/#{seg(email_id)}", body: params)
187
+ end
188
+
189
+ # Reschedule a scheduled email. PATCH /emails/{email_id}
190
+ def reschedule(email_id, scheduled_at)
191
+ @client.request("PATCH", "/emails/#{seg(email_id)}", body: { scheduled_at: scheduled_at })
192
+ end
193
+
194
+ # Cancel a scheduled email. POST /emails/{email_id}/cancel
195
+ def cancel(email_id)
196
+ @client.request("POST", "/emails/#{seg(email_id)}/cancel")
197
+ end
198
+ end
199
+
200
+ class Webhooks < Resource
201
+ # List webhook endpoints. GET /webhooks
202
+ def list
203
+ @client.request("GET", "/webhooks")
204
+ end
205
+
206
+ # Add a webhook endpoint. POST /webhooks
207
+ def create(params)
208
+ @client.request("POST", "/webhooks", body: params)
209
+ end
210
+
211
+ # Get a webhook (with its signing secret). GET /webhooks/{webhook_id}
212
+ def get(webhook_id)
213
+ @client.request("GET", "/webhooks/#{seg(webhook_id)}")
214
+ end
215
+
216
+ # Change a webhook. PATCH /webhooks/{webhook_id}
217
+ def update(webhook_id, params)
218
+ @client.request("PATCH", "/webhooks/#{seg(webhook_id)}", body: params)
219
+ end
220
+
221
+ # Delete a webhook. DELETE /webhooks/{webhook_id}
222
+ def delete(webhook_id)
223
+ @client.request("DELETE", "/webhooks/#{seg(webhook_id)}")
224
+ end
225
+
226
+ # New signing secret. POST /webhooks/{webhook_id}/rotate-secret
227
+ def rotate_secret(webhook_id)
228
+ @client.request("POST", "/webhooks/#{seg(webhook_id)}/rotate-secret")
229
+ end
230
+
231
+ # Send a test email.delivered event. POST /webhooks/{webhook_id}/test
232
+ def test(webhook_id)
233
+ @client.request("POST", "/webhooks/#{seg(webhook_id)}/test")
234
+ end
235
+
236
+ # Latest 100 deliveries. GET /webhooks/{webhook_id}/deliveries
237
+ def deliveries(webhook_id)
238
+ @client.request("GET", "/webhooks/#{seg(webhook_id)}/deliveries")
239
+ end
240
+
241
+ # Deliver an event again. POST /webhook-deliveries/{delivery_id}/replay
242
+ def replay_delivery(delivery_id)
243
+ @client.request("POST", "/webhook-deliveries/#{seg(delivery_id)}/replay")
244
+ end
245
+ end
246
+
247
+ class Suppressions < Resource
248
+ # query: email. GET /suppressions
249
+ def list(query = {})
250
+ @client.request("GET", "/suppressions", body: nil, query: query)
251
+ end
252
+
253
+ # Suppress an address. POST /suppressions
254
+ def create(params)
255
+ @client.request("POST", "/suppressions", body: params)
256
+ end
257
+
258
+ # Remove an address. DELETE /suppressions/{email}
259
+ def delete(email)
260
+ @client.request("DELETE", "/suppressions/#{seg(email)}")
261
+ end
262
+ end
263
+
264
+ class Metrics < Resource
265
+ # query: days, domain. GET /metrics
266
+ def get(query = {})
267
+ @client.request("GET", "/metrics", body: nil, query: query)
268
+ end
269
+ end
270
+
271
+ class Logs < Resource
272
+ # query: source, status, key, limit. GET /logs
273
+ def list(query = {})
274
+ @client.request("GET", "/logs", body: nil, query: query)
275
+ end
276
+ end
277
+
278
+ class Inbox < Resource
279
+ # List folders with counts. GET /mailboxes/{mailbox_id}/folders
280
+ def list_folders(mailbox_id)
281
+ @client.request("GET", "/mailboxes/#{seg(mailbox_id)}/folders")
282
+ end
283
+
284
+ # Create a folder. POST /mailboxes/{mailbox_id}/folders
285
+ def create_folder(mailbox_id, params)
286
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/folders", body: params)
287
+ end
288
+
289
+ # Delete an empty own folder. DELETE /mailboxes/{mailbox_id}/folders/{folder_id}
290
+ def delete_folder(mailbox_id, folder_id)
291
+ @client.request("DELETE", "/mailboxes/#{seg(mailbox_id)}/folders/#{seg(folder_id)}")
292
+ end
293
+
294
+ # query: folder, q, from, unread, flagged, label, message_id, threads, limit, position. GET /mailboxes/{mailbox_id}/messages
295
+ def list_messages(mailbox_id, query = {})
296
+ @client.request("GET", "/mailboxes/#{seg(mailbox_id)}/messages", body: nil, query: query)
297
+ end
298
+
299
+ # Write a new email (or a draft). POST /mailboxes/{mailbox_id}/messages
300
+ def create_message(mailbox_id, params)
301
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/messages", body: params)
302
+ end
303
+
304
+ # Read a message. GET /mailboxes/{mailbox_id}/messages/{message_id}
305
+ def get_message(mailbox_id, message_id)
306
+ @client.request("GET", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}")
307
+ end
308
+
309
+ # Mark, label or move a message. PATCH /mailboxes/{mailbox_id}/messages/{message_id}
310
+ def update_message(mailbox_id, message_id, params)
311
+ @client.request("PATCH", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}", body: params)
312
+ end
313
+
314
+ # Move a message to Deleted Items. DELETE /mailboxes/{mailbox_id}/messages/{message_id}
315
+ def trash_message(mailbox_id, message_id)
316
+ @client.request("DELETE", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}")
317
+ end
318
+
319
+ # Download an attachment (raw bytes). GET /mailboxes/{mailbox_id}/messages/{message_id}/attachments/{blob_id}
320
+ def get_attachment(mailbox_id, message_id, blob_id)
321
+ @client.request("GET", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}/attachments/#{seg(blob_id)}")
322
+ end
323
+
324
+ # Reply in the same thread. POST /mailboxes/{mailbox_id}/messages/{message_id}/reply
325
+ def reply(mailbox_id, message_id, params)
326
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}/reply", body: params)
327
+ end
328
+
329
+ # Forward with the attachments. POST /mailboxes/{mailbox_id}/messages/{message_id}/forward
330
+ def forward(mailbox_id, message_id, params)
331
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}/forward", body: params)
332
+ end
333
+
334
+ # Send a draft. POST /mailboxes/{mailbox_id}/messages/{message_id}/send
335
+ def send_draft(mailbox_id, message_id)
336
+ @client.request("POST", "/mailboxes/#{seg(mailbox_id)}/messages/#{seg(message_id)}/send")
337
+ end
338
+
339
+ # Read a whole conversation. GET /mailboxes/{mailbox_id}/threads/{thread_id}
340
+ def get_thread(mailbox_id, thread_id)
341
+ @client.request("GET", "/mailboxes/#{seg(mailbox_id)}/threads/#{seg(thread_id)}")
342
+ end
343
+ end
344
+
345
+ class Templates < Resource
346
+ # List templates. GET /templates
347
+ def list
348
+ @client.request("GET", "/templates")
349
+ end
350
+
351
+ # Create a template. POST /templates
352
+ def create(params)
353
+ @client.request("POST", "/templates", body: params)
354
+ end
355
+
356
+ # Get a template (id or alias). GET /templates/{template}
357
+ def get(template)
358
+ @client.request("GET", "/templates/#{seg(template)}")
359
+ end
360
+
361
+ # Change the draft. PATCH /templates/{template}
362
+ def update(template, params)
363
+ @client.request("PATCH", "/templates/#{seg(template)}", body: params)
364
+ end
365
+
366
+ # Delete a template and its versions. DELETE /templates/{template}
367
+ def delete(template)
368
+ @client.request("DELETE", "/templates/#{seg(template)}")
369
+ end
370
+
371
+ # Publish the draft as a new version. POST /templates/{template}/publish
372
+ def publish(template)
373
+ @client.request("POST", "/templates/#{seg(template)}/publish")
374
+ end
375
+
376
+ # Copy a template. POST /templates/{template}/duplicate
377
+ def duplicate(template)
378
+ @client.request("POST", "/templates/#{seg(template)}/duplicate")
379
+ end
380
+
381
+ # List published versions. GET /templates/{template}/versions
382
+ def versions(template)
383
+ @client.request("GET", "/templates/#{seg(template)}/versions")
384
+ end
385
+
386
+ # Make an earlier version the published one. POST /templates/{template}/versions/{version}/publish
387
+ def publish_version(template, version)
388
+ @client.request("POST", "/templates/#{seg(template)}/versions/#{seg(version)}/publish")
389
+ end
390
+
391
+ # params: variables, version. POST /templates/{template}/render
392
+ def render(template, params = {})
393
+ @client.request("POST", "/templates/#{seg(template)}/render", body: params)
394
+ end
395
+
396
+ # HTML preview with fallback values. GET /templates/{template}/preview.html
397
+ def preview(template)
398
+ @client.request("GET", "/templates/#{seg(template)}/preview.html")
399
+ end
400
+ end
401
+
402
+ class Contacts < Resource
403
+ # query: segment_id, status, q, limit, position. GET /contacts
404
+ def list(query = {})
405
+ @client.request("GET", "/contacts", body: nil, query: query)
406
+ end
407
+
408
+ # Add or update a contact (by email). POST /contacts
409
+ def create(params)
410
+ @client.request("POST", "/contacts", body: params)
411
+ end
412
+
413
+ # params: csv, mode, from, consent_statement, segment_id. POST /contacts/import
414
+ def import_csv(params)
415
+ @client.request("POST", "/contacts/import", body: params)
416
+ end
417
+
418
+ # Get a contact (id or email). GET /contacts/{contact}
419
+ def get(contact)
420
+ @client.request("GET", "/contacts/#{seg(contact)}")
421
+ end
422
+
423
+ # Change a contact, (un)subscribe, set topics. PATCH /contacts/{contact}
424
+ def update(contact, params)
425
+ @client.request("PATCH", "/contacts/#{seg(contact)}", body: params)
426
+ end
427
+
428
+ # Delete a contact. DELETE /contacts/{contact}
429
+ def delete(contact)
430
+ @client.request("DELETE", "/contacts/#{seg(contact)}")
431
+ end
432
+ end
433
+
434
+ class Segments < Resource
435
+ # List segments. GET /segments
436
+ def list
437
+ @client.request("GET", "/segments")
438
+ end
439
+
440
+ # Create a segment. POST /segments
441
+ def create(params)
442
+ @client.request("POST", "/segments", body: params)
443
+ end
444
+
445
+ # Get a segment. GET /segments/{segment_id}
446
+ def get(segment_id)
447
+ @client.request("GET", "/segments/#{seg(segment_id)}")
448
+ end
449
+
450
+ # Rename a segment. PATCH /segments/{segment_id}
451
+ def update(segment_id, params)
452
+ @client.request("PATCH", "/segments/#{seg(segment_id)}", body: params)
453
+ end
454
+
455
+ # Delete a segment. DELETE /segments/{segment_id}
456
+ def delete(segment_id)
457
+ @client.request("DELETE", "/segments/#{seg(segment_id)}")
458
+ end
459
+
460
+ # Add contacts (ids or emails). POST /segments/{segment_id}/contacts
461
+ def add_contacts(segment_id, contacts)
462
+ @client.request("POST", "/segments/#{seg(segment_id)}/contacts", body: { contacts: contacts })
463
+ end
464
+
465
+ # Remove a contact. DELETE /segments/{segment_id}/contacts/{contact}
466
+ def remove_contact(segment_id, contact)
467
+ @client.request("DELETE", "/segments/#{seg(segment_id)}/contacts/#{seg(contact)}")
468
+ end
469
+ end
470
+
471
+ class Topics < Resource
472
+ # List topics. GET /topics
473
+ def list
474
+ @client.request("GET", "/topics")
475
+ end
476
+
477
+ # Create a topic. POST /topics
478
+ def create(params)
479
+ @client.request("POST", "/topics", body: params)
480
+ end
481
+
482
+ # Delete a topic. DELETE /topics/{topic_id}
483
+ def delete(topic_id)
484
+ @client.request("DELETE", "/topics/#{seg(topic_id)}")
485
+ end
486
+ end
487
+
488
+ class Broadcasts < Resource
489
+ # List broadcasts. GET /broadcasts
490
+ def list
491
+ @client.request("GET", "/broadcasts")
492
+ end
493
+
494
+ # Create a draft broadcast. POST /broadcasts
495
+ def create(params)
496
+ @client.request("POST", "/broadcasts", body: params)
497
+ end
498
+
499
+ # Get a broadcast. GET /broadcasts/{broadcast_id}
500
+ def get(broadcast_id)
501
+ @client.request("GET", "/broadcasts/#{seg(broadcast_id)}")
502
+ end
503
+
504
+ # Change a draft or rejected broadcast. PATCH /broadcasts/{broadcast_id}
505
+ def update(broadcast_id, params)
506
+ @client.request("PATCH", "/broadcasts/#{seg(broadcast_id)}", body: params)
507
+ end
508
+
509
+ # Delete a broadcast. DELETE /broadcasts/{broadcast_id}
510
+ def delete(broadcast_id)
511
+ @client.request("DELETE", "/broadcasts/#{seg(broadcast_id)}")
512
+ end
513
+
514
+ # Send or schedule. params: scheduled_at. POST /broadcasts/{broadcast_id}/send
515
+ def send(broadcast_id, params = {})
516
+ @client.request("POST", "/broadcasts/#{seg(broadcast_id)}/send", body: params)
517
+ end
518
+
519
+ # Cancel (back to draft). POST /broadcasts/{broadcast_id}/cancel
520
+ def cancel(broadcast_id)
521
+ @client.request("POST", "/broadcasts/#{seg(broadcast_id)}/cancel")
522
+ end
523
+
524
+ # Send one test copy. POST /broadcasts/{broadcast_id}/test
525
+ def test(broadcast_id, to)
526
+ @client.request("POST", "/broadcasts/#{seg(broadcast_id)}/test", body: { to: to })
527
+ end
528
+
529
+ # Delivery, open, click and unsubscribe counts. GET /broadcasts/{broadcast_id}/stats
530
+ def stats(broadcast_id)
531
+ @client.request("GET", "/broadcasts/#{seg(broadcast_id)}/stats")
532
+ end
533
+ end
534
+
535
+ class Events < Resource
536
+ # params: event, email or contact_id, first_name, data. POST /events
537
+ def send(params)
538
+ @client.request("POST", "/events", body: params)
539
+ end
540
+
541
+ # query: contact. GET /events
542
+ def list(query = {})
543
+ @client.request("GET", "/events", body: nil, query: query)
544
+ end
545
+ end
546
+
547
+ class Automations < Resource
548
+ # List automations. GET /automations
549
+ def list
550
+ @client.request("GET", "/automations")
551
+ end
552
+
553
+ # Create an automation (draft). POST /automations
554
+ def create(params)
555
+ @client.request("POST", "/automations", body: params)
556
+ end
557
+
558
+ # Get an automation. GET /automations/{automation_id}
559
+ def get(automation_id)
560
+ @client.request("GET", "/automations/#{seg(automation_id)}")
561
+ end
562
+
563
+ # Change a stopped or draft automation. PATCH /automations/{automation_id}
564
+ def update(automation_id, params)
565
+ @client.request("PATCH", "/automations/#{seg(automation_id)}", body: params)
566
+ end
567
+
568
+ # Delete a stopped automation. DELETE /automations/{automation_id}
569
+ def delete(automation_id)
570
+ @client.request("DELETE", "/automations/#{seg(automation_id)}")
571
+ end
572
+
573
+ # Start it. POST /automations/{automation_id}/start
574
+ def start(automation_id)
575
+ @client.request("POST", "/automations/#{seg(automation_id)}/start")
576
+ end
577
+
578
+ # Stop it and every run. POST /automations/{automation_id}/stop
579
+ def stop(automation_id)
580
+ @client.request("POST", "/automations/#{seg(automation_id)}/stop")
581
+ end
582
+
583
+ # Copy it as a draft. POST /automations/{automation_id}/duplicate
584
+ def duplicate(automation_id)
585
+ @client.request("POST", "/automations/#{seg(automation_id)}/duplicate")
586
+ end
587
+
588
+ # query: status. GET /automations/{automation_id}/runs
589
+ def runs(automation_id, query = {})
590
+ @client.request("GET", "/automations/#{seg(automation_id)}/runs", body: nil, query: query)
591
+ end
592
+
593
+ # One run with its step log. GET /automations/{automation_id}/runs/{run_id}
594
+ def get_run(automation_id, run_id)
595
+ @client.request("GET", "/automations/#{seg(automation_id)}/runs/#{seg(run_id)}")
596
+ end
597
+ end
598
+ end
599
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bmailu
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+ require "openssl"
6
+
7
+ module Bmailu
8
+ # Verify Bmailu webhooks (Standard Webhooks / Svix scheme).
9
+ module Webhook
10
+ module_function
11
+
12
+ # Checks the signature and returns the parsed JSON body (string keys).
13
+ # payload: the raw request body. headers: a Hash of request headers (any case).
14
+ # secret: the endpoint's signing secret (whsec_...). Raises Bmailu::WebhookVerificationError.
15
+ def verify(payload, headers, secret, tolerance: 300, now: nil)
16
+ h = {}
17
+ headers.each { |k, v| h[k.to_s.downcase.tr("_", "-").sub(/\Ahttp-/, "")] = Array(v).first.to_s }
18
+ msg_id = h["webhook-id"]
19
+ ts = h["webhook-timestamp"]
20
+ sigs = h["webhook-signature"]
21
+ [["webhook-id", msg_id], ["webhook-timestamp", ts], ["webhook-signature", sigs]].each do |name, value|
22
+ raise WebhookVerificationError, "Missing #{name} header" if value.nil? || value.empty?
23
+ end
24
+ raise WebhookVerificationError, "Bad webhook-timestamp" unless ts.match?(/\A\d+\z/)
25
+ raise WebhookVerificationError, "Timestamp is more than 5 minutes away" if ((now || Time.now.to_i) - ts.to_i).abs > tolerance
26
+
27
+ key = Base64.strict_decode64(secret.sub(/\Awhsec_/, ""))
28
+ body = payload.to_s
29
+ expected = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", key, "#{msg_id}.#{ts}.#{body}"))
30
+ ok = sigs.split(" ").any? do |part|
31
+ version, sig = part.split(",", 2)
32
+ version == "v1" && sig && secure_compare(sig, expected)
33
+ end
34
+ raise WebhookVerificationError, "No matching signature" unless ok
35
+
36
+ body.empty? ? nil : JSON.parse(body)
37
+ rescue ArgumentError
38
+ raise WebhookVerificationError, "Bad secret"
39
+ end
40
+
41
+ def secure_compare(a, b)
42
+ return false unless a.bytesize == b.bytesize
43
+
44
+ r = 0
45
+ a.bytes.zip(b.bytes) { |x, y| r |= x ^ y }
46
+ r.zero?
47
+ end
48
+ end
49
+ end
data/lib/bmailu.rb ADDED
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "uri"
6
+
7
+ require_relative "bmailu/version"
8
+ require_relative "bmailu/error"
9
+ require_relative "bmailu/resource"
10
+ require_relative "bmailu/resources"
11
+ require_relative "bmailu/webhook"
12
+
13
+ # Bmailu Email API client. Standard library only (net/http + json).
14
+ #
15
+ # bmailu = Bmailu::Client.new("bmk_...")
16
+ # bmailu.emails.send({ from: "Shop <hello@shop.com>", to: "ann@example.com", subject: "Hi", html: "<p>Hi</p>" })
17
+ module Bmailu
18
+ DEFAULT_BASE_URL = "https://app.bmailu.com/api/v1"
19
+
20
+ RESOURCES = {
21
+ me: Resources::Me, domains: Resources::Domains, mailboxes: Resources::Mailboxes, aliases: Resources::Aliases,
22
+ api_keys: Resources::ApiKeys, sending_domains: Resources::SendingDomains, emails: Resources::Emails,
23
+ webhooks: Resources::Webhooks, suppressions: Resources::Suppressions, metrics: Resources::Metrics,
24
+ logs: Resources::Logs, inbox: Resources::Inbox, templates: Resources::Templates, contacts: Resources::Contacts,
25
+ segments: Resources::Segments, topics: Resources::Topics, broadcasts: Resources::Broadcasts,
26
+ events: Resources::Events, automations: Resources::Automations
27
+ }.freeze
28
+
29
+ # Shortcut: Bmailu.new(key) is Bmailu::Client.new(key).
30
+ def self.new(*args, **opts)
31
+ Client.new(*args, **opts)
32
+ end
33
+
34
+ class Client
35
+ attr_reader :base_url
36
+
37
+ RESOURCES.each_key { |name| attr_reader name }
38
+
39
+ def initialize(api_key = nil, base_url: nil, timeout: 30)
40
+ @api_key = api_key || ENV["BMAILU_API_KEY"]
41
+ raise ArgumentError, "Missing API key: pass it to Bmailu::Client.new or set BMAILU_API_KEY" if @api_key.nil? || @api_key.empty?
42
+
43
+ @base_url = (base_url || ENV["BMAILU_BASE_URL"] || DEFAULT_BASE_URL).sub(%r{/+\z}, "")
44
+ @timeout = timeout
45
+ RESOURCES.each { |name, klass| instance_variable_set("@#{name}", klass.new(self)) }
46
+ end
47
+
48
+ # Call any endpoint. Returns parsed JSON (string keys), a String for text answers and files.
49
+ def request(method, path, body: nil, query: nil, headers: nil)
50
+ uri = URI(@base_url + (path.start_with?("/") ? path : "/#{path}") + encode_query(query))
51
+ req = Net::HTTPGenericRequest.new(method.to_s.upcase, !body.nil?, true, uri.request_uri)
52
+ req["Authorization"] = "Bearer #{@api_key}"
53
+ req["Content-Type"] = "application/json"
54
+ req["Accept"] = "application/json"
55
+ req["User-Agent"] = "bmailu-ruby/#{VERSION}"
56
+ (headers || {}).each { |k, v| req[k] = v unless v.nil? }
57
+ req.body = JSON.generate(body) unless body.nil?
58
+ res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
59
+ open_timeout: @timeout, read_timeout: @timeout) { |http| http.request(req) }
60
+ handle(res)
61
+ rescue SystemCallError, SocketError, Timeout::Error, IOError, OpenSSL::SSL::SSLError => e
62
+ raise Error.new(0, "connection_error", e.message)
63
+ end
64
+
65
+ private
66
+
67
+ def encode_query(query)
68
+ return "" if query.nil? || query.empty?
69
+
70
+ pairs = query.reject { |_, v| v.nil? }.map { |k, v| [k.to_s, v.to_s] }
71
+ pairs.empty? ? "" : "?#{URI.encode_www_form(pairs)}"
72
+ end
73
+
74
+ def handle(res)
75
+ raw = res.body.to_s
76
+ type = res["Content-Type"].to_s.downcase
77
+ parsed = if raw.empty? then nil
78
+ elsif type.include?("json") then JSON.parse(raw)
79
+ elsif type.start_with?("text/") then raw.dup.force_encoding("UTF-8")
80
+ else raw
81
+ end
82
+ status = res.code.to_i
83
+ return parsed if status >= 200 && status < 300
84
+
85
+ err = parsed.is_a?(Hash) && parsed["error"].is_a?(Hash) ? parsed["error"] : nil
86
+ raise Error.new(status, err["code"].to_s, err["message"].to_s, parsed) if err
87
+
88
+ raise Error.new(status, "http_error", raw[0, 500], parsed)
89
+ end
90
+ end
91
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bmailu
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Bmailu
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-26 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Send email, manage contacts, broadcasts, templates and webhooks with
14
+ the Bmailu API. Standard library only.
15
+ email:
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - bmailu.gemspec
23
+ - lib/bmailu.rb
24
+ - lib/bmailu/error.rb
25
+ - lib/bmailu/resource.rb
26
+ - lib/bmailu/resources.rb
27
+ - lib/bmailu/version.rb
28
+ - lib/bmailu/webhook.rb
29
+ homepage: https://bmailu.com/
30
+ licenses:
31
+ - MIT
32
+ metadata:
33
+ documentation_uri: https://bmailu.com/docs/
34
+ homepage_uri: https://bmailu.com/
35
+ source_code_uri: https://github.com/khiyandev/bmailu-sdks/tree/main/ruby
36
+ bug_tracker_uri: https://github.com/khiyandev/bmailu-sdks/issues
37
+ rubygems_mfa_required: 'true'
38
+ post_install_message:
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '2.7'
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 3.5.22
54
+ signing_key:
55
+ specification_version: 4
56
+ summary: Official Ruby SDK for the Bmailu Email API
57
+ test_files: []