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,52 @@
1
+ require "rails/generators"
2
+ require "rails/generators/migration"
3
+
4
+ module RailsMails
5
+ module Generators
6
+ class InstallGenerator < Rails::Generators::Base
7
+ include Rails::Generators::Migration
8
+
9
+ RECIPIENT_ID_TYPES = %w[bigint uuid string].freeze
10
+
11
+ source_root File.expand_path("templates", __dir__)
12
+ desc "Creates the rails_mails migration and initializer."
13
+
14
+ class_option :mail_logs_table, type: :string, default: "mail_logs"
15
+ class_option :broadcasts_table, type: :string, default: "mail_broadcasts"
16
+ class_option :broadcast_recipients_table, type: :string, default: "mail_broadcast_recipients"
17
+ class_option :recipient_id_type, type: :string, enum: RECIPIENT_ID_TYPES,
18
+ desc: "Column type for recipient_id (defaults to your generators' primary_key_type, else bigint)"
19
+
20
+ def self.next_migration_number(dirname)
21
+ next_migration_number = current_migration_number(dirname) + 1
22
+ ActiveRecord::Migration.next_migration_number(next_migration_number)
23
+ end
24
+
25
+ def create_migration_file
26
+ migration_template "create_rails_mails_tables.rb.tt", "db/migrate/create_rails_mails_tables.rb"
27
+ end
28
+
29
+ def create_initializer
30
+ template "rails_mails.rb.tt", "config/initializers/rails_mails.rb"
31
+ end
32
+
33
+ private
34
+
35
+ def mail_logs_table = options[:mail_logs_table]
36
+ def broadcasts_table = options[:broadcasts_table]
37
+ def broadcast_recipients_table = options[:broadcast_recipients_table]
38
+
39
+ # recipient_id must match the host's primary keys (e.g. UUIDs), like ActiveStorage's
40
+ # install does for record_id.
41
+ def recipient_id_type
42
+ type = options[:recipient_id_type].presence ||
43
+ Rails.application&.config&.generators&.options&.dig(:active_record, :primary_key_type)
44
+ (type || :bigint).to_s
45
+ end
46
+
47
+ def migration_version
48
+ "[#{ActiveRecord::Migration.current_version}]"
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,65 @@
1
+ class CreateRailsMailsTables < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ create_table :<%= mail_logs_table %> do |t|
4
+ t.string :mailer
5
+ t.string :action
6
+ t.string :status, null: false, default: "delivered"
7
+ # `to` stays a string so it can be indexed portably (MySQL can't index text without a
8
+ # prefix length); rails_mails truncates it to 255 characters at an address boundary.
9
+ # cc, bcc and subject can be longer, so they are text.
10
+ t.string :to
11
+ t.text :cc
12
+ t.text :bcc
13
+ t.string :from
14
+ t.string :reply_to
15
+ t.text :subject
16
+ t.text :text_body, limit: 16_777_215
17
+ t.text :html_body, limit: 16_777_215
18
+ t.json :attachments
19
+ t.string :message_id
20
+ t.string :provider_message_id
21
+ t.references :recipient, polymorphic: true, type: :<%= recipient_id_type %>, index: false, foreign_key: false
22
+ t.references :broadcast, index: false, foreign_key: false
23
+ t.text :error, limit: 16_777_215
24
+ t.datetime :created_at, null: false
25
+ end
26
+
27
+ add_index :<%= mail_logs_table %>, :to
28
+ add_index :<%= mail_logs_table %>, :created_at
29
+ add_index :<%= mail_logs_table %>, [ :mailer, :action ]
30
+ add_index :<%= mail_logs_table %>, [ :recipient_type, :recipient_id ]
31
+ add_index :<%= mail_logs_table %>, :broadcast_id
32
+ add_index :<%= mail_logs_table %>, :provider_message_id
33
+
34
+ create_table :<%= broadcasts_table %> do |t|
35
+ t.text :subject
36
+ t.text :body, limit: 16_777_215
37
+ t.string :from
38
+ t.string :reply_to
39
+ t.string :message_stream
40
+ t.integer :recipient_count, null: false, default: 0
41
+ t.bigint :sent_by_id
42
+ t.string :sent_by_label
43
+ t.string :status, null: false, default: "sending"
44
+ t.string :idempotency_key
45
+ t.timestamps
46
+ end
47
+
48
+ add_index :<%= broadcasts_table %>, :idempotency_key, unique: true
49
+
50
+ create_table :<%= broadcast_recipients_table %> do |t|
51
+ t.references :broadcast, null: false, index: false, foreign_key: false
52
+ t.references :recipient, polymorphic: true, type: :<%= recipient_id_type %>, index: false, foreign_key: false
53
+ t.string :email
54
+ t.string :status, null: false, default: "pending"
55
+ t.text :error, limit: 16_777_215
56
+ t.string :skip_reason
57
+ t.integer :attempts, null: false, default: 0
58
+ t.references :mail_log, index: false, foreign_key: false
59
+ t.timestamps
60
+ end
61
+
62
+ add_index :<%= broadcast_recipients_table %>, [ :broadcast_id, :recipient_type, :recipient_id ], unique: true, name: "index_rails_mails_recipients_on_broadcast_and_recipient"
63
+ add_index :<%= broadcast_recipients_table %>, [ :broadcast_id, :status ]
64
+ end
65
+ end
@@ -0,0 +1,72 @@
1
+ # rails_mails configuration. Every option is listed here with its default;
2
+ # uncomment and change what you need. Nothing is stored in the database.
3
+ RailsMails.configure do |config|
4
+ # ---- Access ----------------------------------------------------------
5
+ # Required: the engine returns 403 unless this returns truthy. Receives the controller.
6
+ # config.authorize = ->(controller) { controller.current_user&.admin? }
7
+ # Separate check for sending broadcasts (nil means same as config.authorize).
8
+ # config.authorize_broadcasts = nil
9
+ # Controller the engine inherits from.
10
+ # config.parent_controller = "ActionController::Base"
11
+ # Returns the admin record for the current request (used for "sent by").
12
+ # config.current_admin = ->(controller) { controller.send(:current_user) }
13
+ # Returns the email address used for test sends from an admin record.
14
+ # config.admin_email = ->(admin) { admin.email }
15
+
16
+ # ---- Logging ---------------------------------------------------------
17
+ # Log mail that a delivery interceptor suppressed.
18
+ # config.log_suppressed = true
19
+ # Skip logging when this returns truthy; receives the Mail::Message.
20
+ # config.exclude = ->(message) { false }
21
+
22
+ # ---- Redaction -------------------------------------------------------
23
+ # Mailer classes or modules whose mail bodies are replaced with "[redacted by rails_mails]".
24
+ # Matched by ancestry, so subclasses and mailers including a listed module count too.
25
+ # config.redact_mailers = ["Devise::Mailer", "Devise::Mailers::Helpers"]
26
+ # Custom redaction; receives the message and returns truthy to redact.
27
+ # config.redact = ->(message) { false }
28
+
29
+ # ---- Display ---------------------------------------------------------
30
+ # Default body tab in the log viewer (:text or :html).
31
+ # config.default_view = :text
32
+ # Allow sandboxed HTML previews.
33
+ # config.html_preview = true
34
+ # Block remote images (and all other remote loads) in HTML previews.
35
+ # config.block_remote_images = false
36
+ # Rows per page.
37
+ # config.per_page = 50
38
+
39
+ # ---- Broadcasts ------------------------------------------------------
40
+ # Model name of your recipients, e.g. "User".
41
+ # config.recipient_class = "User"
42
+ # Attribute on the recipient holding the email address.
43
+ # config.recipient_email_attribute = :email
44
+ # Allowed From addresses for broadcasts.
45
+ # config.senders = ["Support <support@example.com>"]
46
+ # Liquid merge fields for each recipient.
47
+ # config.merge_fields = ->(recipient) { { "first_name" => recipient.first_name } }
48
+ # Returns a Liquid::Environment (to register custom filters/tags).
49
+ # config.liquid_environment = -> { Liquid::Environment.default }
50
+ # Maximum recipients per broadcast.
51
+ # config.max_recipients = 500
52
+ # Return a reason string to skip a recipient (falsy to send).
53
+ # config.broadcast_skip_if = ->(recipient) { recipient.emails_off? && "emails off" }
54
+ # Exception class names treated as permanent delivery failures (no retry).
55
+ # config.permanent_delivery_errors = ["Postmark::InactiveRecipientError", "Postmark::ApiInputError"]
56
+ # Exception class names after which the provider may have accepted the mail: the recipient is left "unknown", never retried.
57
+ # config.ambiguous_delivery_errors = ["Net::ReadTimeout", "Net::WriteTimeout", "Postmark::TimeoutError", "EOFError",
58
+ # "Errno::ECONNRESET", "Errno::EPIPE", "OpenSSL::SSL::SSLError"]
59
+ # Attempts before a recipient is marked failed.
60
+ # config.max_delivery_attempts = 5
61
+
62
+ # ActiveJob queue for broadcast jobs. Use a queue your workers process.
63
+ # config.queue_name = "default"
64
+
65
+ # ---- Retention -------------------------------------------------------
66
+ # Purge logs older than this Duration (e.g. 90.days or 1.year); nil keeps everything.
67
+ # config.retain_for = nil
68
+
69
+ # ---- Tables ----------------------------------------------------------
70
+ # Must match the names used in the migration.
71
+ config.table_names = { mail_logs: "<%= mail_logs_table %>", broadcasts: "<%= broadcasts_table %>", broadcast_recipients: "<%= broadcast_recipients_table %>" }
72
+ end
@@ -0,0 +1,251 @@
1
+ require "digest"
2
+
3
+ module RailsMails
4
+ # Creates, cancels and retries broadcasts. Everything the admin previewed is re-checked
5
+ # here on the server: recipients are re-resolved and every message re-rendered.
6
+ module BroadcastSender
7
+ class Invalid < StandardError
8
+ attr_reader :errors
9
+
10
+ def initialize(errors)
11
+ @errors = Array(errors)
12
+ super(@errors.join("; "))
13
+ end
14
+ end
15
+
16
+ MAX_RENDER_ERRORS = 3
17
+ CONTENT_FIELDS = %i[from reply_to subject body recipients].freeze
18
+
19
+ Preview = Data.define(:errors, :resolved, :renderer, :sample)
20
+
21
+ class << self
22
+ def create!(params:, admin:)
23
+ attrs = normalize(params)
24
+ key = attrs[:idempotency_key].to_s.strip
25
+ if key.present? && (existing = Broadcast.find_by(idempotency_key: key))
26
+ return existing
27
+ end
28
+
29
+ errors, resolved, renderer = check(attrs)
30
+ errors << "Missing form token; reload the page and preview again" if key.blank?
31
+ if resolved
32
+ sendable = resolved.sendable
33
+ if resolved.over_limit
34
+ errors << "Too many recipients: #{sendable.size} (max #{RailsMails.config.max_recipients})"
35
+ end
36
+ if sendable.any? && attrs[:confirm_count].to_s.strip.to_i != sendable.size
37
+ errors << "Confirmation count does not match: type #{sendable.size} to send to #{sendable.size} people"
38
+ end
39
+ if renderer && renderer.errors.empty? && !resolved.over_limit
40
+ errors.concat(render_errors(renderer, sendable))
41
+ end
42
+ end
43
+ raise Invalid.new(errors) if errors.any?
44
+
45
+ broadcast = persist!(attrs, resolved, key, admin)
46
+ return broadcast unless broadcast.previously_new_record?
47
+
48
+ begin
49
+ BroadcastFanoutJob.perform_later(broadcast.id)
50
+ rescue StandardError => e
51
+ # The ledger is committed; its rows stay pending and the broadcast page offers Resume.
52
+ Rails.error.report(e, handled: true)
53
+ end
54
+ broadcast
55
+ end
56
+
57
+ # Fingerprint of what the admin previewed. The form carries it next to the idempotency
58
+ # key; a re-preview whose content no longer matches gets a fresh key, so a changed
59
+ # broadcast is never mistaken for a double-submit of the one already sent.
60
+ def content_digest(params)
61
+ attrs = normalize(params)
62
+ Digest::SHA256.hexdigest(CONTENT_FIELDS.map { |field| attrs[field].to_s }.to_json)
63
+ end
64
+
65
+ # Same validation as create! minus idempotency_key/confirm_count. Writes nothing.
66
+ def preview(params:)
67
+ attrs = normalize(params)
68
+ errors, resolved, renderer = check(attrs)
69
+ sample = nil
70
+ if resolved
71
+ sendable = resolved.sendable
72
+ if resolved.over_limit
73
+ errors << "Too many recipients: #{sendable.size} (max #{RailsMails.config.max_recipients})"
74
+ elsif renderer.errors.empty?
75
+ errors.concat(render_errors(renderer, sendable))
76
+ if errors.empty?
77
+ sample = begin
78
+ renderer.render(sendable.first)
79
+ rescue StandardError => e
80
+ errors << e.message
81
+ nil
82
+ end
83
+ end
84
+ end
85
+ end
86
+ Preview.new(errors: errors, resolved: resolved, renderer: renderer, sample: sample)
87
+ end
88
+
89
+ def cancel!(broadcast)
90
+ now = Time.current
91
+ Broadcast.transaction do
92
+ if Broadcast.where(id: broadcast.id, status: "sending").update_all(status: "cancelled", updated_at: now) == 1
93
+ BroadcastRecipient.where(broadcast_id: broadcast.id, status: "pending").update_all(status: "cancelled", updated_at: now)
94
+ end
95
+ end
96
+ broadcast.reload
97
+ end
98
+
99
+ def retry_failed!(broadcast)
100
+ cancelled = Invalid.new([ "Broadcast was cancelled; failed recipients can't be retried" ])
101
+ raise cancelled if Broadcast.where(id: broadcast.id).pick(:status) == "cancelled"
102
+
103
+ now = Time.current
104
+ requeued = Broadcast.transaction do
105
+ count = BroadcastRecipient.where(broadcast_id: broadcast.id, status: "failed")
106
+ .update_all(status: "pending", attempts: 0, error: nil, updated_at: now)
107
+ if count.positive? &&
108
+ Broadcast.where(id: broadcast.id).where.not(status: "cancelled").update_all(status: "sending", updated_at: now) != 1
109
+ raise cancelled # rolls the rows back too
110
+ end
111
+ count
112
+ end
113
+ BroadcastFanoutJob.perform_later(broadcast.id) if requeued.positive?
114
+ broadcast.reload
115
+ end
116
+
117
+ # Re-enqueues the fan-out for a sending broadcast whose pending rows have no job (the
118
+ # fan-out failed to enqueue, jobs were lost, or the adapter could not schedule a retry).
119
+ # Safe to repeat: every delivery job claims its row, so nothing is sent twice.
120
+ def resume!(broadcast)
121
+ status = Broadcast.where(id: broadcast.id).pick(:status)
122
+ raise Invalid.new([ "Broadcast was cancelled; it can't be resumed" ]) if status == "cancelled"
123
+ unless status == "sending" && BroadcastRecipient.where(broadcast_id: broadcast.id, status: "pending").exists?
124
+ raise Invalid.new([ "Nothing to resume: no pending recipients" ])
125
+ end
126
+
127
+ BroadcastFanoutJob.perform_later(broadcast.id)
128
+ broadcast.reload
129
+ end
130
+
131
+ # Sends the first sendable recipient's rendering to the admin. Not tied to a broadcast.
132
+ def send_test!(params:, admin:)
133
+ attrs = normalize(params)
134
+ errors, resolved, renderer = check(attrs)
135
+ to = admin ? RailsMails.config.admin_email.call(admin).to_s.strip : ""
136
+ errors << "No email address for the current admin" if to.empty?
137
+ raise Invalid.new(errors) if errors.any?
138
+
139
+ subject, body = begin
140
+ renderer.render(resolved.sendable.first)
141
+ rescue StandardError => e # TemplateRenderer::Error, or a raising merge_fields lambda
142
+ raise Invalid.new([ e.message ])
143
+ end
144
+ begin
145
+ BroadcastMailer.compose(to: to, from: attrs[:from], reply_to: attrs[:reply_to].to_s.strip.presence,
146
+ subject: subject, body: body).deliver_now
147
+ rescue StandardError => e
148
+ raise Invalid.new([ "Test send failed: #{e.class}: #{e.message}" ])
149
+ end
150
+ end
151
+
152
+ private
153
+
154
+ def normalize(params)
155
+ hash = params.respond_to?(:to_unsafe_h) ? params.to_unsafe_h : params.to_h
156
+ hash.with_indifferent_access
157
+ end
158
+
159
+ # Checks shared by create! and send_test!. Returns [errors, resolved, renderer].
160
+ def check(attrs)
161
+ config = RailsMails.config
162
+ errors = []
163
+ senders = Array(config.senders)
164
+
165
+ if senders.empty?
166
+ errors << "Broadcasts are disabled: no senders configured"
167
+ elsif !senders.include?(attrs[:from])
168
+ errors << "From must be one of the configured senders"
169
+ end
170
+ errors << "Subject can't be blank" if attrs[:subject].to_s.strip.empty?
171
+ errors << "Body can't be blank" if attrs[:body].to_s.strip.empty?
172
+ errors << "Reply-to is not a valid email address" unless valid_reply_to?(attrs[:reply_to])
173
+
174
+ renderer = TemplateRenderer.new(subject: attrs[:subject], body: attrs[:body])
175
+ errors.concat(renderer.errors)
176
+
177
+ resolved = nil
178
+ if config.recipient_class.blank?
179
+ errors << "Broadcasts are disabled: no recipient_class configured"
180
+ else
181
+ resolved = RecipientResolver.call(attrs[:recipients])
182
+ errors << "No recipients to send to" if resolved.sendable.empty?
183
+ end
184
+
185
+ [ errors, resolved, renderer ]
186
+ end
187
+
188
+ def valid_reply_to?(value)
189
+ value = value.to_s.strip
190
+ return true if value.empty?
191
+
192
+ addresses = Mail::AddressList.new(value).addresses
193
+ addresses.any? && addresses.all? { |a| a.address.to_s.include?("@") }
194
+ rescue Mail::Field::ParseError
195
+ false
196
+ end
197
+
198
+ def render_errors(renderer, records)
199
+ errors = []
200
+ records.each do |record|
201
+ renderer.render(record)
202
+ rescue StandardError => e # TemplateRenderer::Error, or a raising merge_fields lambda
203
+ errors << "Could not render for recipient #{record.id}: #{e.message}"
204
+ end
205
+ extra = errors.size - MAX_RENDER_ERRORS
206
+ errors = errors.first(MAX_RENDER_ERRORS)
207
+ errors << "...and #{extra} more recipients that could not be rendered" if extra.positive?
208
+ errors
209
+ end
210
+
211
+ # Writes the broadcast and its whole ledger atomically. A concurrent submit with the
212
+ # same key loses on the unique index and gets the existing broadcast back.
213
+ def persist!(attrs, resolved, key, admin)
214
+ Broadcast.transaction(requires_new: true) do
215
+ broadcast = Broadcast.create!(
216
+ subject: attrs[:subject], body: attrs[:body], from: attrs[:from],
217
+ reply_to: attrs[:reply_to].to_s.strip.presence, status: "sending",
218
+ recipient_count: resolved.sendable.size, idempotency_key: key,
219
+ sent_by_id: admin_id(admin), sent_by_label: admin_label(admin)
220
+ )
221
+ now = Time.current
222
+ rows = resolved.sendable.map { |record| ledger_row(broadcast, record, "pending", nil, now) } +
223
+ resolved.skipped.map { |record, reason| ledger_row(broadcast, record, "skipped", reason, now) }
224
+ BroadcastRecipient.insert_all!(rows)
225
+ broadcast
226
+ end
227
+ rescue ActiveRecord::RecordNotUnique
228
+ Broadcast.find_by(idempotency_key: key) || raise
229
+ end
230
+
231
+ def ledger_row(broadcast, record, status, skip_reason, now)
232
+ {
233
+ broadcast_id: broadcast.id, recipient_type: record.class.polymorphic_name, recipient_id: record.id,
234
+ email: record.public_send(RailsMails.config.recipient_email_attribute).to_s.strip,
235
+ status: status, skip_reason: skip_reason, attempts: 0, created_at: now, updated_at: now
236
+ }
237
+ end
238
+
239
+ def admin_id(admin)
240
+ id = admin.id if admin.respond_to?(:id)
241
+ id if id.is_a?(Integer)
242
+ end
243
+
244
+ def admin_label(admin)
245
+ return nil unless admin
246
+
247
+ RailsMails.config.admin_email.call(admin).to_s.presence
248
+ end
249
+ end
250
+ end
251
+ end
@@ -0,0 +1,74 @@
1
+ module RailsMails
2
+ class Configuration
3
+ DEFAULTS = {
4
+ authorize: nil,
5
+ authorize_broadcasts: nil,
6
+ parent_controller: "ActionController::Base",
7
+ current_admin: -> { ->(c) { c.respond_to?(:current_user, true) ? c.send(:current_user) : nil } },
8
+ admin_email: -> { ->(admin) { admin.respond_to?(:email) ? admin.email : nil } },
9
+ log_suppressed: true,
10
+ exclude: nil,
11
+ # Devise::Mailers::Helpers catches custom Devise mailers that don't inherit Devise::Mailer.
12
+ redact_mailers: -> { [ "Devise::Mailer", "Devise::Mailers::Helpers" ] },
13
+ redact: nil,
14
+ recipient_class: nil,
15
+ recipient_email_attribute: :email,
16
+ table_names: -> { { mail_logs: "mail_logs", broadcasts: "mail_broadcasts", broadcast_recipients: "mail_broadcast_recipients" } },
17
+ default_view: :text,
18
+ html_preview: true,
19
+ block_remote_images: false,
20
+ senders: -> { [] },
21
+ merge_fields: -> { ->(_r) { {} } },
22
+ liquid_environment: -> { -> { Liquid::Environment.default } },
23
+ max_recipients: 500,
24
+ broadcast_skip_if: nil,
25
+ permanent_delivery_errors: -> { [ "Postmark::InactiveRecipientError", "Postmark::ApiInputError" ] },
26
+ # Raised once the request may already have reached the provider.
27
+ ambiguous_delivery_errors: -> {
28
+ [ "Net::ReadTimeout", "Net::WriteTimeout", "Postmark::TimeoutError", "EOFError",
29
+ "Errno::ECONNRESET", "Errno::EPIPE", "OpenSSL::SSL::SSLError" ]
30
+ },
31
+ max_delivery_attempts: 5,
32
+ queue_name: "default",
33
+ retain_for: nil,
34
+ per_page: 50
35
+ }.freeze
36
+
37
+ ATTRIBUTES = DEFAULTS.keys.freeze
38
+
39
+ attr_accessor(*(ATTRIBUTES - [ :authorize_broadcasts ]))
40
+ attr_writer :authorize_broadcasts
41
+
42
+ def initialize
43
+ DEFAULTS.each do |name, default|
44
+ # Lambdas in DEFAULTS are factories for fresh mutable defaults.
45
+ value = default.is_a?(Proc) ? default.call : default
46
+ instance_variable_set(:"@#{name}", value)
47
+ end
48
+ end
49
+
50
+ def authorize_broadcasts
51
+ @authorize_broadcasts || authorize
52
+ end
53
+
54
+ # Rows for the Settings page: [name, display value], Procs masked.
55
+ def to_display
56
+ ATTRIBUTES.map do |name|
57
+ value = instance_variable_get(:"@#{name}")
58
+ shown = name == :authorize_broadcasts && value.nil? ? "same as authorize" : display_value(value)
59
+ [ name.to_s, shown ]
60
+ end
61
+ end
62
+
63
+ private
64
+
65
+ def display_value(value)
66
+ case value
67
+ when nil then "not set"
68
+ when Proc then "custom"
69
+ when String then value
70
+ else value.inspect
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,54 @@
1
+ module RailsMails
2
+ # Mail interceptor that records what happened at the delivery-method boundary, so the
3
+ # observer and the broadcast job never have to guess:
4
+ #
5
+ # - `handed_off?(message)`: the delivery method's `deliver!` returned.
6
+ # - `delivery_error(message)`: it raised (recorded, then re-raised). Mail swallows the
7
+ # error when `raise_delivery_errors` is false and still informs observers, so without
8
+ # this the observer would log a failed send as delivered.
9
+ #
10
+ # The delivery-method object is created per message (Mail dups the default, ActionMailer
11
+ # builds a fresh one), so the singleton wrapper affects only this mail. If an interceptor
12
+ # that runs after this one swaps the delivery method, neither flag is set and callers
13
+ # fall back to treating the outcome as unobserved.
14
+ module DeliveryTracker
15
+ module_function
16
+
17
+ def delivering_email(message)
18
+ # Interceptors run on every delivery attempt, so flags from an earlier attempt of
19
+ # the same message (e.g. an in-process retry after a failure) never leak into this one.
20
+ message.remove_instance_variable(:@rails_mails_delivery_error) if message.instance_variable_defined?(:@rails_mails_delivery_error)
21
+ message.remove_instance_variable(:@rails_mails_handed_off) if message.instance_variable_defined?(:@rails_mails_handed_off)
22
+
23
+ delivery = message.delivery_method
24
+ return if delivery.nil? || delivery.instance_variable_get(:@rails_mails_tracked)
25
+
26
+ original = delivery.method(:deliver!)
27
+ delivery.define_singleton_method(:deliver!) do |mail|
28
+ result = begin
29
+ original.call(mail)
30
+ rescue StandardError => e # recorded, then re-raised unchanged
31
+ mail.instance_variable_set(:@rails_mails_delivery_error, e)
32
+ raise
33
+ end
34
+ mail.instance_variable_set(:@rails_mails_handed_off, true)
35
+ result
36
+ end
37
+ delivery.instance_variable_set(:@rails_mails_tracked, true)
38
+ rescue StandardError => e
39
+ Rails.error.report(e, handled: true)
40
+ end
41
+
42
+ def handed_off?(message)
43
+ message.instance_variable_get(:@rails_mails_handed_off) == true
44
+ end
45
+
46
+ def delivery_error(message)
47
+ message.instance_variable_get(:@rails_mails_delivery_error)
48
+ end
49
+
50
+ def describe(error)
51
+ "#{error.class}: #{error.message}"
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,29 @@
1
+ require "action_mailer"
2
+ require "mail"
3
+ require "rails_mails/message_context"
4
+ require "rails_mails/mailer_hooks"
5
+ require "rails_mails/log_writer"
6
+ require "rails_mails/delivery_tracker"
7
+ require "rails_mails/observer"
8
+
9
+ module RailsMails
10
+ class Engine < ::Rails::Engine
11
+ isolate_namespace RailsMails
12
+
13
+ @capture_installed = false
14
+
15
+ # ActionMailer::Base.register_observer/register_interceptor delegate to Mail, so a single
16
+ # registration on Mail covers ActionMailer mail and raw Mail#deliver exactly once.
17
+ def self.install_capture!
18
+ return if @capture_installed
19
+ @capture_installed = true
20
+ Mail.register_interceptor(RailsMails::DeliveryTracker)
21
+ Mail.register_observer(RailsMails::Observer)
22
+ end
23
+
24
+ initializer "rails_mails.capture" do
25
+ ActiveSupport.on_load(:action_mailer) { include RailsMails::MailerHooks }
26
+ RailsMails::Engine.install_capture!
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,72 @@
1
+ module RailsMails
2
+ module LogWriter
3
+ module_function
4
+
5
+ # Never raises: a logging failure must not affect delivery.
6
+ def write(message, status:, error: nil)
7
+ context = MessageContext.for(message)
8
+ attrs = MessageSerializer.call(message, redacted: redact?(message, context))
9
+ attrs[:to] = truncate_addresses(attrs[:to])
10
+ attrs.merge!(
11
+ mailer: context&.mailer,
12
+ action: context&.action,
13
+ status: status.to_s,
14
+ broadcast_id: context&.broadcast_id,
15
+ error: error
16
+ )
17
+ recipient = context&.recipient || safe_lookup_recipient(attrs[:to])
18
+ attrs[:recipient] = recipient if recipient
19
+
20
+ log = MailLog.create!(attrs)
21
+ message.instance_variable_set(:@rails_mails_log_id, log.id)
22
+ message.instance_variable_set(:@rails_mails_log_status, log.status)
23
+ log
24
+ rescue StandardError => e
25
+ Rails.error.report(e, handled: true)
26
+ nil
27
+ end
28
+
29
+ TO_LIMIT = 255
30
+
31
+ # `to` is an indexed string(255) column (portable across databases, including MySQL), so a
32
+ # very long recipient list is cut at the last whole address that fits. cc/bcc are text.
33
+ def truncate_addresses(value)
34
+ return value if value.nil? || value.length <= TO_LIMIT
35
+
36
+ cut = value[0, TO_LIMIT + 2].rindex(", ")
37
+ cut && cut.positive? ? value[0, cut] : value[0, TO_LIMIT]
38
+ end
39
+
40
+ def redact?(message, context)
41
+ config = RailsMails.config
42
+ redacted_mailer?(context&.mailer) || !!config.redact&.call(message)
43
+ end
44
+
45
+ # Matches by ancestry so subclasses (e.g. `class UserMailer < Devise::Mailer`) are redacted too.
46
+ def redacted_mailer?(name)
47
+ return false if name.blank?
48
+ klass = name.safe_constantize
49
+ Array(RailsMails.config.redact_mailers).any? do |configured|
50
+ configured.to_s == name || (klass && (parent = configured.to_s.safe_constantize) && klass <= parent)
51
+ end
52
+ end
53
+
54
+ def safe_lookup_recipient(to)
55
+ lookup_recipient(to)
56
+ rescue StandardError => e
57
+ Rails.error.report(e, handled: true)
58
+ nil
59
+ end
60
+
61
+ def lookup_recipient(to)
62
+ klass_name = RailsMails.config.recipient_class
63
+ return nil if klass_name.blank?
64
+ addresses = to.to_s.split(",").map(&:strip).reject(&:empty?)
65
+ return nil unless addresses.one?
66
+
67
+ klass = klass_name.to_s.constantize
68
+ column = klass.connection.quote_column_name(RailsMails.config.recipient_email_attribute)
69
+ klass.where("LOWER(#{klass.quoted_table_name}.#{column}) = ?", addresses.first.downcase).first
70
+ end
71
+ end
72
+ end