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
@@ -0,0 +1,196 @@
1
+ module RailsMails
2
+ # Delivers one broadcast email. At-most-once: the job first claims its ledger row with a
3
+ # single conditional UPDATE (pending -> sending). If nothing was claimed it exits, so a
4
+ # duplicate, retried or late job can never send twice. A row only returns to `pending`
5
+ # after an error that means the mail was not handed off. Hand-off is detected at the
6
+ # delivery-method boundary by RailsMails::DeliveryTracker (a Mail interceptor): once
7
+ # `deliver!` returned, the row is `sent` even if something later raises. Errors after which the provider may have accepted it
8
+ # (`ambiguous_delivery_errors`, e.g. a read timeout) leave the row in `sending`
9
+ # ("unknown - check provider") rather than risking a resend.
10
+ #
11
+ # Delivery error precedence: handed off -> sent; permanent -> failed; ambiguous -> left
12
+ # sending; else retried. No hand-off and no error with perform_deliveries false -> failed.
13
+ #
14
+ # No ActiveJob retry_on: retries are bookkept on the row itself.
15
+ class BroadcastDeliveryJob < ActiveJob::Base
16
+ queue_as { RailsMails.config.queue_name }
17
+
18
+ def perform(broadcast_recipient_id)
19
+ # Not claimed: another job owns (or finished) the row. Still finalize, in case it was last.
20
+ return finalize_for(broadcast_recipient_id) unless claim(broadcast_recipient_id)
21
+
22
+ begin
23
+ row = BroadcastRecipient.find(broadcast_recipient_id)
24
+ broadcast = row.broadcast
25
+ record = broadcast && find_recipient(row)
26
+ rescue StandardError => e
27
+ # Nothing has been handed off yet, so this is a plain failure, not "unknown".
28
+ Rails.error.report(e, handled: true)
29
+ mark(broadcast_recipient_id, status: "failed", error: describe(e))
30
+ return finalize_for(broadcast_recipient_id)
31
+ end
32
+ return mark(row.id, status: "failed", error: "broadcast no longer exists") unless broadcast
33
+
34
+ begin
35
+ deliver(row, broadcast, record)
36
+ ensure
37
+ broadcast.finalize_if_done!
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def claim(id)
44
+ attempts = BroadcastRecipient.arel_table[:attempts]
45
+ BroadcastRecipient.where(id: id, status: "pending")
46
+ .update_all(status: "sending", attempts: attempts + 1, updated_at: Time.current) == 1
47
+ end
48
+
49
+ # Moves a row we own (status "sending") to its next state.
50
+ def mark(row_id, **attrs)
51
+ BroadcastRecipient.where(id: row_id, status: "sending").update_all(attrs.merge(updated_at: Time.current)) == 1
52
+ end
53
+
54
+ def mark_sent(row, mail_log_id)
55
+ mark(row.id, status: "sent", error: nil, mail_log_id: mail_log_id)
56
+ end
57
+
58
+ def finalize_for(row_id)
59
+ BroadcastRecipient.find_by(id: row_id)&.broadcast&.finalize_if_done!
60
+ rescue StandardError => e
61
+ Rails.error.report(e, handled: true)
62
+ end
63
+
64
+ def deliver(row, broadcast, record)
65
+ # A cancel that landed after the claim: nothing has been sent yet, so honour it.
66
+ return mark(row.id, status: "cancelled") if broadcast.status == "cancelled"
67
+ return mark(row.id, status: "failed", error: "recipient no longer exists") unless record
68
+ return mark(row.id, status: "failed", error: "recipient has no email address") if row.email.blank?
69
+
70
+ message = nil
71
+ begin
72
+ subject, body = TemplateRenderer.new(subject: broadcast.subject, body: broadcast.body).render(record)
73
+ mail = BroadcastMailer.compose(
74
+ to: row.email, from: broadcast.from, reply_to: broadcast.reply_to,
75
+ subject: subject, body: body, recipient: record, broadcast_id: broadcast.id
76
+ )
77
+ message = mail.message
78
+ rescue TemplateRenderer::Error => e
79
+ # Deterministic: retrying would fail the same way. Nothing was sent.
80
+ return mark(row.id, status: "failed", error: e.message)
81
+ rescue StandardError => e
82
+ # Failed while building; nothing was sent.
83
+ return handle_failure(row, e, nil)
84
+ end
85
+
86
+ begin
87
+ mail.deliver_now
88
+ rescue StandardError => e
89
+ # The delivery method returned, so the provider accepted the mail; whatever raised
90
+ # afterwards (a host notification subscriber, observer or callback) must never
91
+ # cause a resend. A `delivered` log row means the same thing (observers run after
92
+ # hand-off); our own `suppressed` row does not, so suppression is checked first.
93
+ if handed_off?(message)
94
+ Rails.error.report(e, handled: true)
95
+ return mark_sent(row, log_id(message))
96
+ elsif message.perform_deliveries == false
97
+ Rails.error.report(e, handled: true)
98
+ return mark_suppressed(row, message)
99
+ elsif logged_delivered?(message)
100
+ Rails.error.report(e, handled: true)
101
+ return mark_sent(row, log_id(message))
102
+ end
103
+ return handle_failure(row, e, message) if permanent?(e) || !ambiguous?(e)
104
+
105
+ # Outcome unknown: never resend and never claim it failed. Nothing is logged to
106
+ # mail_logs (rows there mean delivered); the row stays "sending" with the error.
107
+ Rails.error.report(e, handled: true)
108
+ return mark(row.id, error: "unknown outcome: #{describe(e)}")
109
+ end
110
+
111
+ if handed_off?(message)
112
+ mark_sent(row, log_id(message))
113
+ elsif message.perform_deliveries == false
114
+ mark_suppressed(row, message)
115
+ else
116
+ # Delivered without passing our tracker (e.g. an interceptor swapped the delivery
117
+ # method). We cannot tell, so never resend and never claim it was sent.
118
+ mark(row.id, error: "unknown outcome: delivery hand-off was not observed", mail_log_id: log_id(message))
119
+ end
120
+ end
121
+
122
+ # A host interceptor or global setting suppressed it: nothing was sent. No retry.
123
+ def mark_suppressed(row, message)
124
+ mark(row.id, status: "failed", error: "suppressed by host (perform_deliveries = false)", mail_log_id: log_id(message))
125
+ end
126
+
127
+ def handed_off?(message)
128
+ DeliveryTracker.handed_off?(message)
129
+ end
130
+
131
+ def log_id(message)
132
+ message.instance_variable_get(:@rails_mails_log_id)
133
+ end
134
+
135
+ def logged_delivered?(message)
136
+ log_id(message) && message.instance_variable_get(:@rails_mails_log_status) == "delivered"
137
+ end
138
+
139
+ def handle_failure(row, error, message)
140
+ Rails.error.report(error, handled: true)
141
+ description = describe(error)
142
+
143
+ if permanent?(error) || row.attempts >= RailsMails.config.max_delivery_attempts
144
+ log = message && LogWriter.write(message, status: "failed", error: description)
145
+ mark(row.id, status: "failed", error: description, mail_log_id: log&.id)
146
+ elsif mark(row.id, status: "pending", error: description)
147
+ # Only re-enqueue once the row is claimable again.
148
+ schedule_retry(row, description)
149
+ end
150
+ end
151
+
152
+ RETRY_NOT_SCHEDULED = "retry not scheduled: queue adapter cannot delay jobs; use Resume".freeze
153
+
154
+ # An adapter that cannot delay jobs (e.g. :inline raises NotImplementedError) or a failed
155
+ # enqueue leaves the row pending with a note; Resume on the broadcast page re-queues it.
156
+ # Enqueuing without a delay is not an option: on :inline that would recurse immediately.
157
+ def schedule_retry(row, description)
158
+ return if self.class.set(wait: (row.attempts**4 + 15).seconds).perform_later(row.id)
159
+
160
+ note_retry_not_scheduled(row, description)
161
+ rescue NotImplementedError, StandardError => e
162
+ Rails.error.report(e, handled: true)
163
+ note_retry_not_scheduled(row, description)
164
+ end
165
+
166
+ def note_retry_not_scheduled(row, description)
167
+ BroadcastRecipient.where(id: row.id, status: "pending")
168
+ .update_all(error: "#{RETRY_NOT_SCHEDULED} (last error: #{description})", updated_at: Time.current)
169
+ end
170
+
171
+ def describe(error)
172
+ DeliveryTracker.describe(error)
173
+ end
174
+
175
+ def permanent?(error)
176
+ matches?(error, RailsMails.config.permanent_delivery_errors)
177
+ end
178
+
179
+ def ambiguous?(error)
180
+ matches?(error, RailsMails.config.ambiguous_delivery_errors)
181
+ end
182
+
183
+ # Matches the error's class or any ancestor by name, so subclasses count too.
184
+ def matches?(error, class_names)
185
+ names = Array(class_names).map(&:to_s)
186
+ error.class.ancestors.any? { |mod| mod.name && names.include?(mod.name) }
187
+ end
188
+
189
+ def find_recipient(row)
190
+ klass = row.recipient_type.to_s.safe_constantize
191
+ return nil unless klass.is_a?(Class) && klass < ActiveRecord::Base
192
+
193
+ klass.find_by(klass.primary_key => row.recipient_id)
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,17 @@
1
+ module RailsMails
2
+ # Enqueues one delivery job per pending recipient. Safe to run more than once:
3
+ # each delivery job claims its row atomically, so duplicate jobs send nothing.
4
+ class BroadcastFanoutJob < ActiveJob::Base
5
+ queue_as { RailsMails.config.queue_name }
6
+
7
+ def perform(broadcast_id)
8
+ broadcast = Broadcast.find_by(id: broadcast_id)
9
+ return unless broadcast&.status == "sending"
10
+
11
+ ids = broadcast.recipients.where(status: "pending").order(:id).pluck(:id)
12
+ ActiveJob.perform_all_later(ids.map { |id| BroadcastDeliveryJob.new(id) }) if ids.any?
13
+ # Nothing pending (e.g. every recipient skipped) means the broadcast is already done.
14
+ broadcast.finalize_if_done!
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,17 @@
1
+ module RailsMails
2
+ # Plain-text, layout-free mailer used for broadcasts so each message reads like a 1:1 email.
3
+ class BroadcastMailer < ActionMailer::Base
4
+ def compose(to:, from:, reply_to:, subject:, body:, recipient: nil, broadcast_id: nil)
5
+ rails_mails_recipient(recipient) if recipient
6
+ @rails_mails_broadcast_id = broadcast_id
7
+
8
+ headers = { to: to, from: from, subject: subject }
9
+ headers[:reply_to] = reply_to if reply_to.present?
10
+ mail(headers) { |format| format.text { render plain: body } }
11
+ # The per-recipient ledger must see delivery errors even when the host sets
12
+ # raise_delivery_errors = false (a global cattr, so set per message), or a failed
13
+ # send would be recorded as sent.
14
+ message.raise_delivery_errors = true
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,5 @@
1
+ module RailsMails
2
+ class ApplicationRecord < ActiveRecord::Base
3
+ self.abstract_class = true
4
+ end
5
+ end
@@ -0,0 +1,26 @@
1
+ module RailsMails
2
+ class Broadcast < ApplicationRecord
3
+ self.table_name = RailsMails.config.table_names.fetch(:broadcasts)
4
+
5
+ STATUSES = %w[sending sent cancelled].freeze
6
+
7
+ has_many :recipients, class_name: "RailsMails::BroadcastRecipient", foreign_key: :broadcast_id, inverse_of: :broadcast, dependent: :delete_all
8
+ has_many :mail_logs, class_name: "RailsMails::MailLog", foreign_key: :broadcast_id, inverse_of: :broadcast
9
+
10
+ def counts_by_status
11
+ recipients.group(:status).count
12
+ end
13
+
14
+ # Flips sending -> sent once no row is pending or sending. A single conditional UPDATE,
15
+ # so it never overwrites a concurrent cancel or races a retry that re-queued rows.
16
+ def finalize_if_done!
17
+ unfinished = BroadcastRecipient.where(broadcast_id: id, status: %w[pending sending])
18
+ updated = self.class.where(id: id, status: "sending").where(unfinished.arel.exists.not)
19
+ .update_all(status: "sent", updated_at: Time.current)
20
+ return unless updated == 1
21
+
22
+ self.status = "sent"
23
+ clear_attribute_changes([ :status ])
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,16 @@
1
+ module RailsMails
2
+ class BroadcastRecipient < ApplicationRecord
3
+ self.table_name = RailsMails.config.table_names.fetch(:broadcast_recipients)
4
+
5
+ STATUSES = %w[pending sending sent failed skipped cancelled].freeze
6
+
7
+ belongs_to :broadcast, class_name: "RailsMails::Broadcast", inverse_of: :recipients
8
+ belongs_to :recipient, polymorphic: true, optional: true
9
+ belongs_to :mail_log, class_name: "RailsMails::MailLog", optional: true
10
+
11
+ # A row stuck in "sending" is shown as "unknown - check provider".
12
+ def stale_sending?
13
+ status == "sending" && updated_at < 15.minutes.ago
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,53 @@
1
+ module RailsMails
2
+ class MailLog < ApplicationRecord
3
+ self.table_name = RailsMails.config.table_names.fetch(:mail_logs)
4
+
5
+ STATUSES = %w[delivered suppressed failed].freeze
6
+
7
+ belongs_to :recipient, polymorphic: true, optional: true
8
+ belongs_to :broadcast, class_name: "RailsMails::Broadcast", optional: true
9
+
10
+ scope :search, ->(q) {
11
+ like = "%#{sanitize_sql_like(q.to_s.downcase, "!")}%"
12
+ where("LOWER(#{quoted_column(:to)}) LIKE :q ESCAPE '!' OR LOWER(#{quoted_column(:subject)}) LIKE :q ESCAPE '!'", q: like)
13
+ }
14
+ scope :for_mailer_action, ->(value) {
15
+ mailer, action = value.to_s.split("#", 2)
16
+ where(mailer: mailer, action: action)
17
+ }
18
+ # Exact address within the ", "-joined `to` column; portable across databases. Addresses
19
+ # are stored downcased, so the column is compared as-is: the equality arm (single-recipient
20
+ # mail, the common case) can use the `to` index; the LIKE arms find multi-recipient rows.
21
+ scope :to_address, ->(address) {
22
+ a = address.to_s.strip.downcase
23
+ col = quoted_column(:to)
24
+ esc = sanitize_sql_like(a, "!")
25
+ where("#{col} = :a OR #{col} LIKE :first ESCAPE '!' OR #{col} LIKE :last ESCAPE '!' OR #{col} LIKE :mid ESCAPE '!'",
26
+ a: a, first: "#{esc}, %", last: "%, #{esc}", mid: "%, #{esc}, %")
27
+ }
28
+ scope :with_status, ->(status) { where(status: status) }
29
+ scope :between, ->(from_date, to_date) {
30
+ where(created_at: from_date.to_date.beginning_of_day..to_date.to_date.end_of_day)
31
+ }
32
+
33
+ def self.quoted_column(name)
34
+ "#{quoted_table_name}.#{connection.quote_column_name(name)}"
35
+ end
36
+
37
+ def self.sent?(to:, mailer:, action:, since:)
38
+ address = to.to_s.strip.downcase
39
+ return false if address.empty?
40
+
41
+ pattern = "%#{sanitize_sql_like(address, "!")}%"
42
+ where(mailer: mailer, action: action, created_at: since..)
43
+ .where("#{quoted_column(:to)} LIKE ? ESCAPE '!'", pattern)
44
+ .pluck(:to)
45
+ .any? { |value| value.to_s.downcase.split(",").map(&:strip).include?(address) }
46
+ end
47
+
48
+ # Rows are immutable once written.
49
+ def readonly?
50
+ persisted? || super
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,47 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Mail log</title>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <%= csrf_meta_tags %>
7
+ <style<%= raw %( nonce="#{ERB::Util.html_escape(content_security_policy_nonce)}") if content_security_policy_nonce.present? %>>
8
+ body { font: 13px/1.5 -apple-system, "Helvetica Neue", Arial, sans-serif; margin: 0; color: #222; background: #f4f4f4; }
9
+ nav { background: #2b2b2b; padding: 0 20px; }
10
+ nav a { color: #ddd; display: inline-block; padding: 10px 14px; text-decoration: none; }
11
+ nav a:hover { background: #444; color: #fff; }
12
+ main { padding: 20px; max-width: 1200px; margin: 0 auto; }
13
+ h1 { font-size: 20px; margin: 0 0 14px; }
14
+ table { border-collapse: collapse; width: 100%; background: #fff; }
15
+ th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #e3e3e3; vertical-align: top; }
16
+ th { background: #efefef; font-weight: 600; }
17
+ a { color: #1c5fa8; }
18
+ form.rm-filters { margin-bottom: 14px; background: #fff; padding: 10px; }
19
+ form.rm-filters input, form.rm-filters select { margin-right: 8px; padding: 3px; }
20
+ .rm-status { padding: 1px 8px; border-radius: 10px; font-size: 12px; background: #ddd; }
21
+ .rm-delivered { background: #cdebd2; } .rm-suppressed { background: #f5e4b3; } .rm-failed { background: #f3c5c5; }
22
+ .rm-meta th { width: 160px; }
23
+ .rm-body { background: #fff; padding: 14px; border: 1px solid #e3e3e3; }
24
+ .rm-frame { width: 100%; height: 600px; border: 1px solid #e3e3e3; background: #fff; }
25
+ .rm-help { color: #555; }
26
+ .rm-error { background: #f3c5c5; padding: 6px 10px; }
27
+ .rm-notice { background: #cdebd2; padding: 6px 10px; }
28
+ .rm-preview { margin-top: 20px; }
29
+ .rm-sending { background: #cfe0f5; } .rm-sent { background: #cdebd2; } .rm-cancelled { background: #ddd; }
30
+ .rm-pager { margin-top: 12px; }
31
+ </style>
32
+ </head>
33
+ <body>
34
+ <nav>
35
+ <%= link_to "Logs", mail_logs_path %>
36
+ <% if can_broadcast? %>
37
+ <%= link_to "Broadcasts", broadcasts_path %>
38
+ <% end %>
39
+ <%= link_to "Settings", settings_path %>
40
+ </nav>
41
+ <main>
42
+ <% if flash[:notice] %><p class="rm-notice"><%= flash[:notice] %></p><% end %>
43
+ <% if flash[:alert] %><p class="rm-error"><%= flash[:alert] %></p><% end %>
44
+ <%= yield %>
45
+ </main>
46
+ </body>
47
+ </html>
@@ -0,0 +1,23 @@
1
+ <p class="rm-help">For transactional notices to a specific group of users (e.g. a change to their account, plugin or device). Not for feature announcements or marketing.</p>
2
+
3
+ <%= form_with url: preview_broadcasts_path, method: :post, local: true, class: "rm-form" do |f| %>
4
+ <p>
5
+ <label>From<br>
6
+ <%= select_tag :from, options_for_select(Array(RailsMails.config.senders), @form[:from]) %>
7
+ </label>
8
+ </p>
9
+ <p><label>Reply-to (optional)<br><%= text_field_tag :reply_to, @form[:reply_to], size: 50 %></label></p>
10
+ <p><label>Subject<br><%= text_field_tag :subject, @form[:subject], size: 80 %></label></p>
11
+ <p><label>Body<br><%= text_area_tag :body, @form[:body], rows: 12, cols: 80 %></label></p>
12
+ <% variables = rails_mails_merge_field_names %>
13
+ <% if variables.any? %>
14
+ <p class="rm-help">Available variables: <%= variables.map { |v| "{{ #{v} }}" }.join(", ") %></p>
15
+ <% end %>
16
+ <p><label>Recipients (user IDs or email addresses, separated by commas, spaces or new lines)<br>
17
+ <%= text_area_tag :recipients, @form[:recipients], rows: 6, cols: 80 %></label></p>
18
+ <% if @idempotency_key %>
19
+ <%= hidden_field_tag :idempotency_key, @idempotency_key, id: "preview_idempotency_key" %>
20
+ <%= hidden_field_tag :content_digest, @content_digest, id: "preview_content_digest" %>
21
+ <% end %>
22
+ <p><%= submit_tag "Preview" %></p>
23
+ <% end %>
@@ -0,0 +1,58 @@
1
+ <% resolved = @resolved %>
2
+ <% sendable = resolved.sendable.size %>
3
+ <% errors = @preview[:errors] %>
4
+ <% sendable_ok = errors.empty? && !resolved.over_limit && sendable.positive? %>
5
+ <div class="rm-preview">
6
+ <h2>Preview</h2>
7
+
8
+ <% if @errors.present? || errors.any? %>
9
+ <ul class="rm-error">
10
+ <% (@errors.to_a + errors).uniq.each do |error| %><li><%= error %></li><% end %>
11
+ </ul>
12
+ <% end %>
13
+
14
+ <p><strong><%= pluralize(sendable, "recipient") %></strong> will receive this.</p>
15
+ <% if resolved.over_limit %>
16
+ <p class="rm-error">Too many recipients: <%= sendable %> (max <%= RailsMails.config.max_recipients %>). Remove some and preview again.</p>
17
+ <% end %>
18
+ <% if resolved.unknown.any? %>
19
+ <p>Unknown (not found, will not be sent): <%= resolved.unknown.join(", ") %></p>
20
+ <% end %>
21
+ <% if resolved.duplicates.positive? %>
22
+ <p><%= pluralize(resolved.duplicates, "duplicate") %> ignored.</p>
23
+ <% end %>
24
+ <% if resolved.skipped.any? %>
25
+ <p>Skipped (<%= resolved.skipped.size %>):</p>
26
+ <ul>
27
+ <% resolved.skipped.each do |record, reason| %>
28
+ <li><%= record.public_send(RailsMails.config.recipient_email_attribute) %> (<%= reason %>)</li>
29
+ <% end %>
30
+ </ul>
31
+ <% end %>
32
+
33
+ <% if @preview[:sample] %>
34
+ <% subject, body = @preview[:sample] %>
35
+ <table class="rm-meta">
36
+ <tr><th>Subject</th><td><%= subject %></td></tr>
37
+ </table>
38
+ <div class="rm-body"><%= rails_mails_plain_text(body) %></div>
39
+ <% end %>
40
+
41
+ <% if sendable_ok %>
42
+ <%= form_with url: test_send_broadcasts_path, method: :post, local: true do %>
43
+ <% @form.each do |key, value| %><%= hidden_field_tag key, value, id: "test_#{key}" %><% end %>
44
+ <%= hidden_field_tag :idempotency_key, @idempotency_key, id: "test_idempotency_key" %>
45
+ <%= hidden_field_tag :content_digest, @content_digest, id: "test_content_digest" %>
46
+ <%= submit_tag "Send test to me" %>
47
+ <% end %>
48
+
49
+ <%= form_with url: broadcasts_path, method: :post, local: true do %>
50
+ <% @form.each do |key, value| %><%= hidden_field_tag key, value, id: "send_#{key}" %><% end %>
51
+ <%= hidden_field_tag :idempotency_key, @idempotency_key, id: "send_idempotency_key" %>
52
+ <%= hidden_field_tag :content_digest, @content_digest, id: "send_content_digest" %>
53
+ <p><label>Type <%= sendable %> to send to <%= sendable %> people<br>
54
+ <%= text_field_tag :confirm_count, nil, autocomplete: "off", size: 6 %></label></p>
55
+ <%= submit_tag "Send" %>
56
+ <% end %>
57
+ <% end %>
58
+ </div>
@@ -0,0 +1,21 @@
1
+ <h1>Broadcasts <%= link_to "New broadcast", new_broadcast_path, style: "font-size: 13px; margin-left: 12px;" %></h1>
2
+
3
+ <table>
4
+ <tr><th>ID</th><th>Created</th><th>Subject</th><th>Status</th><th>Recipients</th><th>Counts</th></tr>
5
+ <% @broadcasts.each do |broadcast| %>
6
+ <% counts = ->(status) { @counts[[ broadcast.id, status ]].to_i } %>
7
+ <tr>
8
+ <td><%= link_to "##{broadcast.id}", broadcast_path(broadcast) %></td>
9
+ <td><%= rails_mails_time(broadcast.created_at) %></td>
10
+ <td><%= broadcast.subject %></td>
11
+ <td><span class="<%= rails_mails_status_class(broadcast.status) %>"><%= broadcast.status %></span></td>
12
+ <td><%= broadcast.recipient_count %></td>
13
+ <td><%= RailsMails::BroadcastRecipient::STATUSES.filter_map { |st| "#{st}: #{counts.(st)}" if counts.(st).positive? }.join(", ") %></td>
14
+ </tr>
15
+ <% end %>
16
+ </table>
17
+
18
+ <p class="rm-pager">
19
+ <% if @page > 1 %><%= link_to "Previous", broadcasts_path(page: @page - 1) %><% end %>
20
+ <% if @has_next %><%= link_to "Next", broadcasts_path(page: @page + 1) %><% end %>
21
+ </p>
@@ -0,0 +1,5 @@
1
+ <h1>New broadcast</h1>
2
+ <%= render "form" %>
3
+ <% if @preview %>
4
+ <%= render "preview" %>
5
+ <% end %>
@@ -0,0 +1,47 @@
1
+ <h1>Broadcast #<%= @broadcast.id %></h1>
2
+
3
+ <table class="rm-meta">
4
+ <tr><th>Status</th><td><span class="<%= rails_mails_status_class(@broadcast.status) %>"><%= @broadcast.status %></span></td></tr>
5
+ <tr><th>Subject</th><td><%= @broadcast.subject %></td></tr>
6
+ <tr><th>From</th><td><%= @broadcast.from %></td></tr>
7
+ <tr><th>Reply-To</th><td><%= @broadcast.reply_to %></td></tr>
8
+ <tr><th>Sent by</th><td><%= @broadcast.sent_by_label %></td></tr>
9
+ <tr><th>Created</th><td><%= rails_mails_time(@broadcast.created_at) %></td></tr>
10
+ <tr><th>Counts</th><td><%= @counts.sort.map { |status, n| "#{status}: #{n}" }.join(", ") %></td></tr>
11
+ </table>
12
+
13
+ <div class="rm-body"><%= rails_mails_plain_text(@broadcast.body) %></div>
14
+
15
+ <p>
16
+ <% if @broadcast.status == "sending" %>
17
+ <%= button_to "Cancel", cancel_broadcast_path(@broadcast), method: :post, form: { style: "display: inline", onsubmit: "return confirm('Cancel this broadcast?')" } %>
18
+ <% end %>
19
+ <% if @broadcast.status == "sending" && @counts["pending"].to_i.positive? %>
20
+ <%= button_to "Resume", resume_broadcast_path(@broadcast), method: :post, form: { style: "display: inline" } %>
21
+ <% end %>
22
+ <% if @counts["failed"].to_i.positive? && @broadcast.status != "cancelled" %>
23
+ <%= button_to "Retry failed", retry_failed_broadcast_path(@broadcast), method: :post, form: { style: "display: inline" } %>
24
+ <% end %>
25
+ </p>
26
+ <% if @broadcast.status == "sending" && @counts["pending"].to_i.positive? %>
27
+ <p class="rm-help">Resume re-queues pending recipients whose jobs never ran (for example, the queue was down or restarted). It is safe to press: no recipient is ever sent twice.</p>
28
+ <% end %>
29
+
30
+ <h2>Recipients</h2>
31
+ <table>
32
+ <tr><th>Email</th><th>Status</th><th>Detail</th><th>Mail</th></tr>
33
+ <% @recipients.each do |row| %>
34
+ <tr>
35
+ <td><%= row.email %></td>
36
+ <td>
37
+ <span class="<%= rails_mails_status_class(row.status) %>"><%= row.status %></span>
38
+ <% if rails_mails_unknown_outcome?(row) %> unknown — check provider<% end %>
39
+ </td>
40
+ <td><%= row.skip_reason.presence || row.error %></td>
41
+ <td><%= link_to "Log ##{row.mail_log_id}", mail_log_path(row.mail_log_id) if row.mail_log_id %></td>
42
+ </tr>
43
+ <% end %>
44
+ </table>
45
+ <% if @broadcast.recipients.count > @recipients.size %>
46
+ <p class="rm-help">Showing the first <%= @recipients.size %> recipients.</p>
47
+ <% end %>
@@ -0,0 +1,36 @@
1
+ <h1>Mail logs</h1>
2
+
3
+ <%= form_with url: mail_logs_path, method: :get, class: "rm-filters" do |f| %>
4
+ <%= f.search_field :q, value: params[:q], placeholder: "Search to / subject" %>
5
+ <%= f.text_field :to, value: params[:to], placeholder: "Exact address" %>
6
+ <%= f.select :mailer_action, @mailer_actions, { include_blank: "All mailers", selected: params[:mailer_action] } %>
7
+ <%= f.select :status, RailsMails::MailLog::STATUSES, { include_blank: "Any status", selected: params[:status] } %>
8
+ <%= f.date_field :from_date, value: params[:from_date] %>
9
+ <%= f.date_field :to_date, value: params[:to_date] %>
10
+ <%= f.submit "Filter", name: nil %>
11
+ <% end %>
12
+
13
+ <table>
14
+ <thead>
15
+ <tr><th>Time</th><th>To</th><th>Mailer#action</th><th>Subject</th><th>Status</th></tr>
16
+ </thead>
17
+ <tbody>
18
+ <% @logs.each do |log| %>
19
+ <tr>
20
+ <td><%= rails_mails_time(log.created_at) %></td>
21
+ <td><%= log.to %></td>
22
+ <td><%= log.mailer %>#<%= log.action %></td>
23
+ <td><%= link_to log.subject.presence || "(no subject)", mail_log_path(log) %></td>
24
+ <td><span class="<%= rails_mails_status_class(log.status) %>"><%= log.status %></span></td>
25
+ </tr>
26
+ <% end %>
27
+ <% if @logs.empty? %>
28
+ <tr><td colspan="5">No mail logged.</td></tr>
29
+ <% end %>
30
+ </tbody>
31
+ </table>
32
+
33
+ <div class="rm-pager">
34
+ <% if @page > 1 %><%= link_to "Previous", mail_logs_path(request.query_parameters.merge("page" => @page - 1)) %><% end %>
35
+ <% if @has_next %><%= link_to "Next", mail_logs_path(request.query_parameters.merge("page" => @page + 1)) %><% end %>
36
+ </div>
@@ -0,0 +1,32 @@
1
+ <h1><%= @log.subject.presence || "(no subject)" %></h1>
2
+
3
+ <table class="rm-meta">
4
+ <tr><th>Time</th><td><%= rails_mails_time(@log.created_at) %></td></tr>
5
+ <tr><th>Mailer#action</th><td><%= @log.mailer %>#<%= @log.action %></td></tr>
6
+ <tr><th>Status</th><td><span class="<%= rails_mails_status_class(@log.status) %>"><%= @log.status %></span><% if @log.error.present? %> <%= @log.error %><% end %></td></tr>
7
+ <tr><th>To</th><td><%= @log.to %></td></tr>
8
+ <tr><th>Cc</th><td><%= @log.cc %></td></tr>
9
+ <tr><th>Bcc</th><td><%= @log.bcc %></td></tr>
10
+ <tr><th>From</th><td><%= @log.from %></td></tr>
11
+ <tr><th>Reply-To</th><td><%= @log.reply_to %></td></tr>
12
+ <tr><th>Message-ID</th><td><%= @log.message_id %></td></tr>
13
+ <tr><th>Provider message ID</th><td><%= @log.provider_message_id %></td></tr>
14
+ <tr><th>Attachments</th><td><%= Array(@log.attachments).map { |a| "#{a["filename"]} (#{a["content_type"]})" }.join(", ") %></td></tr>
15
+ <tr><th>Recipient</th><td><%= rails_mails_recipient_link(@log) %></td></tr>
16
+ <tr><th>Broadcast</th><td><%= rails_mails_broadcast_link(@log) %></td></tr>
17
+ </table>
18
+
19
+ <p>
20
+ <% if @html_available %>
21
+ <%= link_to "Text", mail_log_path(@log, view: "text") %> |
22
+ <%= link_to "HTML", mail_log_path(@log, view: "html") %>
23
+ <% end %>
24
+ </p>
25
+
26
+ <% if @view == "html" %>
27
+ <%= rails_mails_iframe(@log.html_body) %>
28
+ <% else %>
29
+ <div class="rm-body"><%= rails_mails_body_text(@log.text_body) %></div>
30
+ <% end %>
31
+
32
+ <p><%= link_to "Back to logs", mail_logs_path %></p>
@@ -0,0 +1,10 @@
1
+ <h1>Settings</h1>
2
+ <p>Effective configuration (read-only). Change it in <code>config/initializers/rails_mails.rb</code>.</p>
3
+ <table>
4
+ <thead><tr><th>Setting</th><th>Value</th></tr></thead>
5
+ <tbody>
6
+ <% @rows.each do |name, value| %>
7
+ <tr><td><code><%= name %></code></td><td><%= value %></td></tr>
8
+ <% end %>
9
+ </tbody>
10
+ </table>
data/config/routes.rb ADDED
@@ -0,0 +1,16 @@
1
+ RailsMails::Engine.routes.draw do
2
+ root "mail_logs#index"
3
+ resources :mail_logs, only: %i[index show]
4
+ resources :broadcasts, only: %i[index new create show] do
5
+ collection do
6
+ post :preview
7
+ post :test_send
8
+ end
9
+ member do
10
+ post :cancel
11
+ post :retry_failed
12
+ post :resume
13
+ end
14
+ end
15
+ resource :settings, only: :show
16
+ end