rails_mails 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.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +15 -0
  3. data/LICENSE +20 -0
  4. data/README.md +236 -0
  5. data/app/controllers/rails_mails/application_controller.rb +24 -0
  6. data/app/controllers/rails_mails/broadcasts_controller.rb +113 -0
  7. data/app/controllers/rails_mails/mail_logs_controller.rb +39 -0
  8. data/app/controllers/rails_mails/settings_controller.rb +7 -0
  9. data/app/helpers/rails_mails/application_helper.rb +87 -0
  10. data/app/jobs/rails_mails/broadcast_delivery_job.rb +196 -0
  11. data/app/jobs/rails_mails/broadcast_fanout_job.rb +17 -0
  12. data/app/mailers/rails_mails/broadcast_mailer.rb +17 -0
  13. data/app/models/rails_mails/application_record.rb +5 -0
  14. data/app/models/rails_mails/broadcast.rb +26 -0
  15. data/app/models/rails_mails/broadcast_recipient.rb +16 -0
  16. data/app/models/rails_mails/mail_log.rb +53 -0
  17. data/app/views/layouts/rails_mails/application.html.erb +47 -0
  18. data/app/views/rails_mails/broadcasts/_form.html.erb +23 -0
  19. data/app/views/rails_mails/broadcasts/_preview.html.erb +58 -0
  20. data/app/views/rails_mails/broadcasts/index.html.erb +21 -0
  21. data/app/views/rails_mails/broadcasts/new.html.erb +5 -0
  22. data/app/views/rails_mails/broadcasts/show.html.erb +47 -0
  23. data/app/views/rails_mails/mail_logs/index.html.erb +36 -0
  24. data/app/views/rails_mails/mail_logs/show.html.erb +32 -0
  25. data/app/views/rails_mails/settings/show.html.erb +10 -0
  26. data/config/routes.rb +16 -0
  27. data/lib/generators/rails_mails/install/install_generator.rb +52 -0
  28. data/lib/generators/rails_mails/install/templates/create_rails_mails_tables.rb.tt +65 -0
  29. data/lib/generators/rails_mails/install/templates/rails_mails.rb.tt +72 -0
  30. data/lib/rails_mails/broadcast_sender.rb +251 -0
  31. data/lib/rails_mails/configuration.rb +74 -0
  32. data/lib/rails_mails/delivery_tracker.rb +54 -0
  33. data/lib/rails_mails/engine.rb +29 -0
  34. data/lib/rails_mails/log_writer.rb +72 -0
  35. data/lib/rails_mails/mailer_hooks.rb +32 -0
  36. data/lib/rails_mails/message_context.rb +7 -0
  37. data/lib/rails_mails/message_serializer.rb +69 -0
  38. data/lib/rails_mails/observer.rb +21 -0
  39. data/lib/rails_mails/purge.rb +24 -0
  40. data/lib/rails_mails/recipient_resolver.rb +75 -0
  41. data/lib/rails_mails/template_renderer.rb +48 -0
  42. data/lib/rails_mails/version.rb +3 -0
  43. data/lib/rails_mails.rb +25 -0
  44. data/lib/tasks/rails_mails_tasks.rake +6 -0
  45. metadata +230 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 113e7f2a40372850454f9bef990237fd53d696bc65fec995bca06bcad2b77584
4
+ data.tar.gz: 79d00a3dee0041670923e51a28e5327f27b8688f2bbe6cb716e2de9292cce261
5
+ SHA512:
6
+ metadata.gz: d466fe81b6d36d9ff28d76d20ad8ade1d365dc901767f687f93148fbbec70234c862762594583b2686a5cd8076132f9217785c764839acb8504ad968dc532e98
7
+ data.tar.gz: ec037cccd681341a1821efc1a56354e39a7ce3208cd2acd463eef12e11e9d8c392b069da5a64761bae7a493eb7ba9548a0d173d5a4b777312a937f8340d602f7
data/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release.
6
+
7
+ - Mail log: every email delivered by a Rails app (including Devise and other gems' mailers, and raw `Mail.deliver`) is recorded, with a built-in admin UI (list, search, filters, text/HTML view in a sandboxed iframe). A `delivered` row means the delivery method accepted the message; with `raise_delivery_errors = false`, mail whose delivery method raised is logged as `failed` with the error. Suppressed mail (`perform_deliveries = false`) is logged as `suppressed` (configurable).
8
+ - Addresses are stored downcased; `to` is an indexed string truncated at an address boundary, `cc`/`bcc`/`subject` are text.
9
+ - Redaction of sensitive mailers (`Devise::Mailer` and `Devise::Mailers::Helpers` by default, matched by ancestry) while keeping metadata.
10
+ - Broadcasts: transactional 1:1 emails to a pasted list of users, with Liquid merge fields, preview, test send, typed-count confirmation, a content-bound idempotency key, per-recipient tracking, cancel, retry-failed and resume.
11
+ - At-most-once delivery with an explicit "unknown - check provider" state; connection resets, broken pipes, EOF and SSL errors are treated as ambiguous and never retried automatically.
12
+ - Requires a persistent ActiveJob backend for broadcasts (jobs run on `config.queue_name`, default `"default"`); on adapters that cannot delay jobs, transient retries are left pending for Resume instead of crashing.
13
+ - Retention: `rails_mails:purge` rake task driven by `config.retain_for` (an `ActiveSupport::Duration`).
14
+ - Install generator with a fully commented initializer, configurable table names, and `recipient_id` typed from the host's `primary_key_type` (or `--recipient-id-type=bigint|uuid|string`).
15
+ - Supports Ruby 3.2+ and Rails 7.1 through 8.1 (tested on SQLite and PostgreSQL).
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2026 ryanckulp
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,236 @@
1
+ # RailsMails
2
+
3
+ A mountable Rails engine that does two jobs:
4
+
5
+ 1. **Mail log.** Every email your app hands to its delivery method is written to a table, so an admin can answer "did we send this user that email, and what did it say?" without opening Postmark or SendGrid.
6
+ 2. **Broadcasts.** An admin writes a short plaintext message, pastes a list of user IDs or emails, picks an approved "send as" address, and the gem sends one 1:1 transactional email per user, with per-recipient tracking.
7
+
8
+ It ships its own small server-rendered admin UI, so it works with ActiveAdmin, Administrate, or no admin framework at all. No JavaScript build, asset pipeline, or pagination gem is required.
9
+
10
+ Requires Ruby 3.2+ and Rails 7.1+.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ bundle add rails_mails
16
+ rails g rails_mails:install
17
+ rails db:migrate
18
+ ```
19
+
20
+ The generator creates a migration and `config/initializers/rails_mails.rb`, with every option present and commented.
21
+
22
+ Generator options:
23
+
24
+ | Flag | Default | |
25
+ |---|---|---|
26
+ | `--mail-logs-table=NAME` | `mail_logs` | Table names. If `mail_logs` is already taken in your app, pick another; the names are written to the initializer's `config.table_names`, which must match the migration. |
27
+ | `--broadcasts-table=NAME` | `mail_broadcasts` | |
28
+ | `--broadcast-recipients-table=NAME` | `mail_broadcast_recipients` | |
29
+ | `--recipient-id-type=bigint\|uuid\|string` | your `primary_key_type`, else `bigint` | Column type of `recipient_id` (the polymorphic link to your users). |
30
+
31
+ **UUID primary keys:** if your app sets `config.generators { |g| g.orm :active_record, primary_key_type: :uuid }`, the migration's `recipient_id` columns are created as `uuid` automatically (as ActiveStorage does). Otherwise pass `--recipient-id-type=uuid` (or `string`). The gem's own tables keep integer primary keys.
32
+
33
+ ## Mount and authorize
34
+
35
+ The engine refuses every request with a 403 unless `config.authorize` returns truthy, so it is never open by accident. Do both: mount it behind your own auth, and set `config.authorize`.
36
+
37
+ With Devise, in `config/routes.rb`:
38
+
39
+ ```ruby
40
+ authenticated :user, ->(u) { u.admin? } do
41
+ mount RailsMails::Engine => "/admin/mails"
42
+ end
43
+ ```
44
+
45
+ And in `config/initializers/rails_mails.rb`:
46
+
47
+ ```ruby
48
+ config.authorize = ->(controller) { controller.current_user&.admin? }
49
+ ```
50
+
51
+ Sending broadcasts can be gated separately, so support staff can read logs without being able to email your user base:
52
+
53
+ ```ruby
54
+ config.authorize_broadcasts = ->(controller) { controller.current_user&.superadmin? }
55
+ ```
56
+
57
+ It defaults to `config.authorize`. Broadcast links are hidden when it fails.
58
+
59
+ ### ActiveAdmin
60
+
61
+ Add a menu item in `config/initializers/active_admin.rb`:
62
+
63
+ ```ruby
64
+ config.namespace :admin do |admin|
65
+ admin.build_menu do |menu|
66
+ menu.add label: "Mail Logs", url: "/admin/mails"
67
+ end
68
+ end
69
+ ```
70
+
71
+ To link from a user page, use the deep-link helper:
72
+
73
+ ```ruby
74
+ rails_mails.mail_logs_path(to: user.email)
75
+ ```
76
+
77
+ ## What gets logged
78
+
79
+ The gem registers a Mail observer (plus an interceptor that watches the delivery method), so it sees mail from every mailer: yours, Devise's, and other gems'. Mail sent with raw `Mail.deliver` is logged too, with no mailer name.
80
+
81
+ - A `delivered` row means the delivery method accepted the message (its `deliver!` returned). If the delivery method raises, nothing is logged as delivered: normally the error propagates and no row is written; if your app sets `raise_delivery_errors = false` (so Mail swallows the error), the row is written as `failed` with the error.
82
+ - Mail suppressed with `perform_deliveries = false` is logged with status `suppressed` when `config.log_suppressed` is true (the default), which answers "why didn't I get it?". Set it to `false` to skip those.
83
+ - Rows are immutable: there is no edit or delete in the UI, and no `updated_at`.
84
+ - Bodies are stored as text (and HTML when present). Attachments are stored as filenames and content types only.
85
+ - Addresses are stored as plain, downcased, comma-joined addresses. `to` is an indexed `string(255)` column; a longer recipient list is cut at the last whole address that fits. `cc`, `bcc` and `subject` are `text`.
86
+ - Logging never raises into delivery: any error while writing a log row is reported through `Rails.error.report` and swallowed.
87
+
88
+ The log records what the app handed to the provider, not what the provider did with it afterwards (bounces are not tracked).
89
+
90
+ To associate a log with a record explicitly, call `rails_mails_recipient(user)` inside a mailer action. Otherwise, when `config.recipient_class` is set and the message has exactly one `to` address, the gem looks the record up by `config.recipient_email_attribute`.
91
+
92
+ To check whether something was already sent:
93
+
94
+ ```ruby
95
+ RailsMails::MailLog.sent?(to: user.email, mailer: "UserMailer", action: "welcome", since: 1.day.ago)
96
+ ```
97
+
98
+ ## Redaction
99
+
100
+ Password-reset, unlock and confirmation emails contain working token links. Anyone who can read the log could use them, so by default `Devise::Mailer` and `Devise::Mailers::Helpers` (matched by ancestry, so any subclass of `Devise::Mailer` and any custom mailer that includes Devise's helpers) are logged with full metadata (to, subject, mailer, action, time, status) but the body is replaced with `[redacted by rails_mails]`. Support still sees "reset email sent at 14:02" without being handed an account takeover.
101
+
102
+ Add your own mailers with `config.redact_mailers`, or use `config.redact` for finer cases such as magic links:
103
+
104
+ ```ruby
105
+ config.redact_mailers = ["Devise::Mailer", "Devise::Mailers::Helpers", "MagicLinkMailer"]
106
+ config.redact = ->(message) { message.subject.to_s.include?("sign-in link") }
107
+ ```
108
+
109
+ HTML bodies are only ever shown inside `<iframe sandbox srcdoc="...">` with an empty `sandbox` attribute (no scripts, no same-origin access, no top navigation), never inline in the admin page.
110
+
111
+ ## Configuration reference
112
+
113
+ Everything is configured in `config/initializers/rails_mails.rb`. Nothing is stored in the database. The admin UI has a read-only Settings page showing the effective values (procs are shown as "custom").
114
+
115
+ | Option | Default | Description |
116
+ |---|---|---|
117
+ | `authorize` | `nil` | Required. `->(controller) { ... }`; the engine returns 403 unless it is truthy. |
118
+ | `authorize_broadcasts` | falls back to `authorize` | Separate gate for composing, sending, cancelling, retrying and resuming broadcasts. Settings shows "same as authorize" when unset. |
119
+ | `parent_controller` | `"ActionController::Base"` | Controller the engine inherits from (so `current_user` etc. are available). |
120
+ | `current_admin` | calls `current_user` if the controller has it | `->(controller) { ... }` returning the admin record; used for "sent by". |
121
+ | `admin_email` | `->(admin) { admin.email }` | Address used for "Send test to me". |
122
+ | `log_suppressed` | `true` | Log mail suppressed with `perform_deliveries = false` as `suppressed`. |
123
+ | `exclude` | `nil` | `->(message) { ... }`; skip logging when truthy. |
124
+ | `redact_mailers` | `["Devise::Mailer", "Devise::Mailers::Helpers"]` | Mailer classes or modules whose bodies are redacted (matched by ancestry: subclasses and mailers including a listed module count). |
125
+ | `redact` | `nil` | `->(message) { ... }`; redact the body when truthy. |
126
+ | `recipient_class` | `nil` | Model name of your recipients, e.g. `"User"`. Required for broadcasts; also used to associate logs. |
127
+ | `recipient_email_attribute` | `:email` | Attribute holding the email address. |
128
+ | `table_names` | `{ mail_logs: "mail_logs", broadcasts: "mail_broadcasts", broadcast_recipients: "mail_broadcast_recipients" }` | Must match the migration. |
129
+ | `default_view` | `:text` | Default body tab in the log viewer (`:text` or `:html`). |
130
+ | `html_preview` | `true` | Set `false` to hide the HTML view entirely. |
131
+ | `block_remote_images` | `false` | Block remote images (and every other remote load) in HTML previews via a CSP: `default-src 'none'; img-src data:; style-src 'unsafe-inline'`. |
132
+ | `per_page` | `50` | Rows per page. |
133
+ | `senders` | `[]` | Allowed From addresses, e.g. `["Support <support@example.com>"]`. An empty list disables broadcasts. |
134
+ | `merge_fields` | `->(_recipient) { {} }` | Returns a hash of Liquid variables for a recipient (values are coerced to strings). |
135
+ | `liquid_environment` | `-> { Liquid::Environment.default }` | Returns the `Liquid::Environment` used to parse templates. |
136
+ | `max_recipients` | `500` | Hard cap per broadcast. |
137
+ | `broadcast_skip_if` | `nil` | `->(recipient) { ... }`; return a reason string to skip a recipient. |
138
+ | `permanent_delivery_errors` | `["Postmark::InactiveRecipientError", "Postmark::ApiInputError"]` | Exception class names meaning the provider rejected this recipient; marked failed, not retried. |
139
+ | `ambiguous_delivery_errors` | `["Net::ReadTimeout", "Net::WriteTimeout", "Postmark::TimeoutError", "EOFError", "Errno::ECONNRESET", "Errno::EPIPE", "OpenSSL::SSL::SSLError"]` | Exception class names after which the provider may have accepted the mail; the recipient is left "unknown", never retried. |
140
+ | `max_delivery_attempts` | `5` | Attempts before a recipient is marked failed. |
141
+ | `queue_name` | `"default"` | ActiveJob queue for broadcast jobs. Set it to a queue your workers process. |
142
+ | `retain_for` | `nil` | Purge logs older than this; must be a Duration such as `90.days` or `1.year` (a bare Integer raises `ArgumentError`). `nil` keeps everything. |
143
+
144
+ ## Broadcasts
145
+
146
+ Broadcasts are for **transactional notices to a small, specific group**: "users with plugin X enabled, here is a change to your account". Typical size is a few dozen, never thousands. They are not for feature announcements or marketing, and v1 sends everything through your normal (transactional) delivery settings.
147
+
148
+ Configure the minimum:
149
+
150
+ ```ruby
151
+ config.recipient_class = "User"
152
+ config.senders = ["Support <support@example.com>"]
153
+ config.merge_fields = ->(user) { { "first_name" => user.first_name } }
154
+ ```
155
+
156
+ The compose form takes a From (chosen from `config.senders`), an optional Reply-To, a subject, a plaintext body, and a list of recipients (IDs or emails separated by commas, spaces or newlines). Every entry must resolve to a `recipient_class` record; unknown entries are listed and not sent.
157
+
158
+ ### Merge fields
159
+
160
+ Subject and body are [Liquid](https://shopify.github.io/liquid/) templates:
161
+
162
+ ```
163
+ Hi {{ first_name | default: "there" }},
164
+ ```
165
+
166
+ Variables come only from `config.merge_fields`, a hash whose values are coerced to strings; templates never get the record itself. Templates render with strict variables and strict filters, so a typo raises at preview and blocks sending.
167
+
168
+ To use extra filters or tags, return your own Liquid environment, e.g. an app-specific Liquid environment with custom filters:
169
+
170
+ ```ruby
171
+ config.liquid_environment = -> { TRMNL::Liquid.new }
172
+ ```
173
+
174
+ ### Compose, preview, send
175
+
176
+ 1. **Preview** resolves the recipients and shows the resolved count, unknown inputs, duplicates removed, recipients skipped by `broadcast_skip_if`, and the rendered email for the first recipient. **Send test to me** emails the rendered message to the current admin (not logged against the broadcast).
177
+ 2. **Send** requires typing the recipient count to confirm. `config.max_recipients` is a hard cap, enforced at preview and at send, as a guard against pasting the wrong list.
178
+ 3. A double-click or double-submit creates only one broadcast (the form carries an idempotency key). The key is tied to the previewed content: if you go back, change the message or recipients and preview again, you get a new key, so the changed broadcast is sent rather than mistaken for a duplicate.
179
+ 4. A fan-out job enqueues one job per recipient on your ActiveJob adapter. Each email is `text/plain` with no layout, so it reads like a 1:1 message.
180
+
181
+ Broadcasts need a **persistent ActiveJob backend** (Sidekiq, Solid Queue, GoodJob, ...). The default `:async` adapter keeps jobs in memory, so a restart loses them; `:inline` cannot schedule the delayed retries used for transient errors (the recipient is left `pending` with "retry not scheduled ... use Resume").
182
+
183
+ Do not call `RailsMails::BroadcastSender.create!` inside your own database transaction: the fan-out can run before your transaction commits and find no rows.
184
+
185
+ On the broadcast page you can:
186
+
187
+ - **Cancel** a sending broadcast: remaining pending recipients become `cancelled`; in-flight jobs see that and exit.
188
+ - **Retry failed**: re-queues recipients marked `failed`.
189
+ - **Resume** a sending broadcast that still has `pending` recipients whose jobs never ran (the fan-out could not be enqueued, the queue lost jobs or restarted, or a retry could not be scheduled). It re-runs the fan-out; it is always safe, because each job claims its recipient row and nothing is sent twice.
190
+
191
+ A broadcast becomes `sent` once no recipient is pending or sending.
192
+
193
+ ### At-most-once delivery, and "unknown — check provider"
194
+
195
+ A missed email is better than a duplicate, so each recipient is a row in a ledger written before anything is sent. A job claims its row with a single conditional update (`pending` to `sending`); if nothing is claimed it exits, so duplicate or retried jobs can never send twice.
196
+
197
+ - If the mail was handed to the delivery method, the row is `sent` and linked to its log, even if something later raises.
198
+ - **Permanent errors** (`permanent_delivery_errors`, e.g. the provider rejects the address) mark the recipient `failed` immediately, and a `failed` log row is written.
199
+ - **Transient errors** (nothing was handed off, e.g. `Net::OpenTimeout`, `Errno::ECONNREFUSED`, `SocketError`) put the row back to `pending` and retry with backoff, up to `max_delivery_attempts`, then `failed`.
200
+ - **Ambiguous errors** (`ambiguous_delivery_errors`, e.g. a read timeout, a connection reset or a broken pipe) mean the request may have reached the provider. The row stays `sending` and the UI shows **unknown — check provider**. The same applies when the hand-off could not be observed, and to rows stuck in `sending` for over 15 minutes. These are never retried automatically: look the recipient up at your provider and resend by hand if it never went out.
201
+
202
+ ## Retention
203
+
204
+ By default logs are kept forever. Set a retention window and schedule the rake task:
205
+
206
+ ```ruby
207
+ config.retain_for = 1.year # a Duration, not an Integer
208
+ ```
209
+
210
+ ```bash
211
+ bin/rails rails_mails:purge # prints "rails_mails: purged N mail logs"
212
+ ```
213
+
214
+ Schedule it with whatever you use (cron, sidekiq-cron, Solid Queue recurring tasks). It deletes mail logs older than `retain_for` in batches of 1,000 and is a no-op when `retain_for` is `nil`. Broadcasts and their recipient records are kept; a recipient whose log was purged simply shows no log link. From code, `RailsMails::Purge.call(older_than: 90.days)` returns the number of rows deleted.
215
+
216
+ ## Postmark notes
217
+
218
+ - The provider message id is captured from the `X-PM-Message-Id` header (set by postmark-rails after a successful send) and stored in `provider_message_id`, so you can find the message in Postmark's activity feed.
219
+ - The default `permanent_delivery_errors`, and some of the `ambiguous_delivery_errors`, name Postmark exception classes. They are matched by name (including subclasses), so postmark-rails is not a dependency. Adjust them for other providers.
220
+ - Message streams are a future feature. Broadcasts currently use your default (transactional) stream; a broadcast stream needs unsubscribe handling, which is not built yet.
221
+
222
+ ## Development
223
+
224
+ ```bash
225
+ bin/rails test
226
+ ```
227
+
228
+ Tests run against SQLite by default; CI also runs Postgres.
229
+
230
+ ## Contributing
231
+
232
+ Bug reports and pull requests are welcome at https://github.com/ryanckulp/rails_mails.
233
+
234
+ ## License
235
+
236
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,24 @@
1
+ module RailsMails
2
+ class ApplicationController < RailsMails.config.parent_controller.constantize
3
+ protect_from_forgery with: :exception
4
+
5
+ layout "rails_mails/application"
6
+
7
+ before_action :rails_mails_authorize!
8
+ helper RailsMails::ApplicationHelper
9
+ helper_method :can_broadcast?
10
+
11
+ private
12
+
13
+ def rails_mails_authorize!
14
+ return if RailsMails.config.authorize&.call(self)
15
+
16
+ render plain: "Forbidden", status: :forbidden
17
+ end
18
+
19
+ def can_broadcast?
20
+ config = RailsMails.config
21
+ !!(Array(config.senders).any? && config.recipient_class && config.authorize_broadcasts&.call(self))
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,113 @@
1
+ module RailsMails
2
+ class BroadcastsController < ApplicationController
3
+ before_action { head :forbidden unless can_broadcast? }
4
+ before_action :set_broadcast, only: %i[show cancel retry_failed resume]
5
+
6
+ FORM_FIELDS = BroadcastSender::CONTENT_FIELDS
7
+
8
+ def index
9
+ page = [ params[:page].to_i, 1 ].max
10
+ @broadcasts, @has_next = helpers.rails_mails_pagination(Broadcast.order(id: :desc), page)
11
+ @page = page
12
+ @counts = BroadcastRecipient.where(broadcast_id: @broadcasts.map(&:id)).group(:broadcast_id, :status).count
13
+ end
14
+
15
+ def new
16
+ @form = {}
17
+ end
18
+
19
+ def preview
20
+ @form = form_params
21
+ issue_idempotency_key
22
+ build_preview
23
+ render :new
24
+ end
25
+
26
+ def create
27
+ @form = form_params
28
+ @idempotency_key = params[:idempotency_key].to_s
29
+ @content_digest = BroadcastSender.content_digest(@form)
30
+ # Deliberately not in a transaction: the fan-out job is enqueued after create!'s own commit.
31
+ broadcast = BroadcastSender.create!(params: form_params.merge(
32
+ idempotency_key: @idempotency_key, confirm_count: params[:confirm_count]
33
+ ), admin: rails_mails_admin)
34
+ if broadcast.previously_new_record?
35
+ redirect_to broadcast_path(broadcast)
36
+ else
37
+ redirect_to broadcast_path(broadcast), notice: "This broadcast was already submitted — showing the original."
38
+ end
39
+ rescue BroadcastSender::Invalid => e
40
+ @errors = e.errors
41
+ build_preview
42
+ render :new, status: 422
43
+ end
44
+
45
+ def test_send
46
+ @form = form_params
47
+ issue_idempotency_key
48
+ begin
49
+ BroadcastSender.send_test!(params: form_params, admin: rails_mails_admin)
50
+ flash.now[:notice] = "Test email sent to #{RailsMails.config.admin_email.call(rails_mails_admin)}"
51
+ rescue BroadcastSender::Invalid => e
52
+ flash.now[:alert] = e.errors.join("; ")
53
+ end
54
+ build_preview
55
+ render :new
56
+ end
57
+
58
+ def show
59
+ @counts = @broadcast.counts_by_status
60
+ @recipients = @broadcast.recipients.includes(:mail_log).order(:id).limit(1000).to_a
61
+ end
62
+
63
+ def cancel
64
+ BroadcastSender.cancel!(@broadcast)
65
+ redirect_to broadcast_path(@broadcast), notice: "Broadcast cancelled"
66
+ rescue BroadcastSender::Invalid => e
67
+ redirect_to broadcast_path(@broadcast), alert: e.message
68
+ end
69
+
70
+ def retry_failed
71
+ BroadcastSender.retry_failed!(@broadcast)
72
+ redirect_to broadcast_path(@broadcast), notice: "Failed recipients re-queued"
73
+ rescue BroadcastSender::Invalid => e
74
+ redirect_to broadcast_path(@broadcast), alert: e.message
75
+ end
76
+
77
+ def resume
78
+ BroadcastSender.resume!(@broadcast)
79
+ redirect_to broadcast_path(@broadcast), notice: "Pending recipients re-queued"
80
+ rescue BroadcastSender::Invalid => e
81
+ redirect_to broadcast_path(@broadcast), alert: e.message
82
+ end
83
+
84
+ private
85
+
86
+ # Reuses the posted key only while the content is what was previewed with it.
87
+ def issue_idempotency_key
88
+ @content_digest = BroadcastSender.content_digest(@form)
89
+ posted = params[:idempotency_key].presence
90
+ @idempotency_key = posted && params[:content_digest].to_s == @content_digest ? posted : SecureRandom.uuid
91
+ end
92
+
93
+ def set_broadcast
94
+ @broadcast = Broadcast.find(params[:id])
95
+ end
96
+
97
+ def rails_mails_admin
98
+ RailsMails.config.current_admin&.call(self)
99
+ end
100
+
101
+ def form_params
102
+ params.slice(*FORM_FIELDS).permit(*FORM_FIELDS).to_h.symbolize_keys
103
+ end
104
+
105
+ # Read-only: validates exactly as create! would. Creates nothing.
106
+ def build_preview
107
+ @errors ||= []
108
+ result = BroadcastSender.preview(params: @form)
109
+ @preview = { errors: result.errors, sample: result.sample }
110
+ @resolved = result.resolved || RecipientResolver::Result.new(sendable: [], skipped: [], unknown: [], duplicates: 0, over_limit: false)
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,39 @@
1
+ module RailsMails
2
+ class MailLogsController < ApplicationController
3
+ def index
4
+ logs = MailLog.order(created_at: :desc, id: :desc)
5
+ logs = logs.search(params[:q]) if params[:q].present?
6
+ logs = logs.to_address(params[:to]) if params[:to].present?
7
+ logs = logs.for_mailer_action(params[:mailer_action]) if params[:mailer_action].present?
8
+ logs = logs.with_status(params[:status]) if MailLog::STATUSES.include?(params[:status])
9
+ from, to = parse_date(params[:from_date]), parse_date(params[:to_date])
10
+ logs = logs.where(created_at: from.beginning_of_day..) if from
11
+ logs = logs.where(created_at: ..to.end_of_day) if to
12
+ @page = params[:page].to_s.to_i.clamp(1, 10_000)
13
+ @logs, @has_next = helpers.rails_mails_pagination(logs, @page)
14
+ @mailer_actions = mailer_actions
15
+ end
16
+
17
+ def show
18
+ @log = MailLog.find(params[:id])
19
+ requested = params[:view].presence || RailsMails.config.default_view.to_s
20
+ @html_available = RailsMails.config.html_preview && @log.html_body.present?
21
+ @view = requested == "html" && @html_available ? "html" : "text"
22
+ end
23
+
24
+ private
25
+
26
+ # DISTINCT over the whole table is too slow to run on every page load.
27
+ def mailer_actions
28
+ Rails.cache.fetch("rails_mails/mailer_actions/#{MailLog.table_name}", expires_in: 10.minutes) do
29
+ MailLog.distinct.order(:mailer, :action).pluck(:mailer, :action).map { |m, a| "#{m}##{a}" }
30
+ end
31
+ end
32
+
33
+ def parse_date(value)
34
+ value.present? ? Date.iso8601(value.to_s) : nil
35
+ rescue ArgumentError
36
+ nil
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,7 @@
1
+ module RailsMails
2
+ class SettingsController < ApplicationController
3
+ def show
4
+ @rows = RailsMails.config.to_display
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,87 @@
1
+ module RailsMails
2
+ module ApplicationHelper
3
+ # Inline images and styles only: no remote images, fonts, stylesheets or frames.
4
+ REMOTE_BLOCKING_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'".freeze
5
+
6
+ def rails_mails_body_text(text)
7
+ escaped = ERB::Util.html_escape(text.to_s)
8
+ escaped = escaped.gsub(/\*\*(.+?)\*\*/m) { "<strong>#{$1}</strong>" }
9
+ escaped.gsub(/\r\n|\r|\n/, "<br>").html_safe
10
+ end
11
+
12
+ # Plaintext with line breaks; escaped, no formatting.
13
+ def rails_mails_plain_text(text)
14
+ ERB::Util.html_escape(text.to_s).gsub(/\r\n|\r|\n/, "<br>").html_safe
15
+ end
16
+
17
+ def rails_mails_iframe(html)
18
+ doc = html.to_s
19
+ if RailsMails.config.block_remote_images
20
+ meta = %(<meta http-equiv="Content-Security-Policy" content="#{REMOTE_BLOCKING_CSP}">)
21
+ # After `<head>` / `<head ...>` (never `<header>`); without a head, after any leading
22
+ # doctype and `<html>` so the document doesn't drop into quirks mode.
23
+ head = /<head(?:\s[^>]*)?>/i
24
+ if doc.match?(head)
25
+ doc = doc.sub(head) { |tag| "#{tag}#{meta}" }
26
+ else
27
+ prefix = doc[/\A\s*(?:<!doctype[^>]*>\s*)?(?:<html(?:\s[^>]*)?>)?/i].to_s
28
+ doc = prefix + meta + doc[prefix.length..]
29
+ end
30
+ end
31
+ tag.iframe(sandbox: "", srcdoc: doc, class: "rm-frame", title: "Email HTML preview")
32
+ end
33
+
34
+ # Returns [records, has_next].
35
+ def rails_mails_pagination(scope, page)
36
+ per = RailsMails.config.per_page
37
+ records = scope.offset((page - 1) * per).limit(per + 1).to_a
38
+ [ records.first(per), records.size > per ]
39
+ end
40
+
41
+ def rails_mails_time(time)
42
+ time&.in_time_zone&.strftime("%Y-%m-%d %H:%M:%S %Z")
43
+ end
44
+
45
+ def rails_mails_status_class(status)
46
+ "rm-status rm-#{status}"
47
+ end
48
+
49
+ def rails_mails_recipient_link(log)
50
+ return "-" if log.recipient_type.blank?
51
+
52
+ label = "#{log.recipient_type} ##{log.recipient_id}"
53
+ return label unless log.recipient_type.safe_constantize
54
+
55
+ record = log.recipient
56
+ return "#{label} (deleted)" if record.nil?
57
+
58
+ begin
59
+ link_to label, main_app.polymorphic_path(record)
60
+ rescue NoMethodError, ActionController::UrlGenerationError
61
+ label
62
+ end
63
+ rescue ActiveRecord::ActiveRecordError
64
+ "#{label} (deleted)"
65
+ end
66
+
67
+ def rails_mails_broadcast_link(log)
68
+ return "-" unless log.broadcast_id
69
+
70
+ label = "Broadcast ##{log.broadcast_id}"
71
+ can_broadcast? ? link_to(label, broadcast_path(log.broadcast_id)) : label
72
+ end
73
+
74
+ # Keys of merge_fields for a sample recipient, or [] when there is none.
75
+ def rails_mails_merge_field_names
76
+ klass = RailsMails.config.recipient_class.to_s.safe_constantize
77
+ sample = klass&.first
78
+ sample ? RailsMails.config.merge_fields.call(sample).keys.map(&:to_s) : []
79
+ rescue StandardError
80
+ []
81
+ end
82
+
83
+ def rails_mails_unknown_outcome?(row)
84
+ row.status == "sending" && (row.stale_sending? || row.error.to_s.start_with?("unknown outcome"))
85
+ end
86
+ end
87
+ end