email_digest_agent.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. require 'net/smtp'
  2. module Agents
  3. class EmailDigestAgent < Agent
  4. include EmailConcern
  5. default_schedule "5am"
  6. cannot_create_events!
  7. description <<~MD
  8. The Email Digest Agent collects any Events sent to it and sends them all via email when scheduled. The number of
  9. used events also relies on the `Keep events` option of the emitting Agent, meaning that if events expire before
  10. this agent is scheduled to run, they will not appear in the email.
  11. By default, the email will have a `subject` and an optional `headline` before listing the Events. If the Events'
  12. payloads contain a `message`, that will be highlighted, otherwise everything in
  13. their payloads will be shown.
  14. You can specify one or more `recipients` for the email, or skip the option in order to send the email to your
  15. account's default email address.
  16. You can provide a `from` address for the email, or leave it blank to default to the value of `EMAIL_FROM_ADDRESS` (`#{ENV['EMAIL_FROM_ADDRESS']}`).
  17. You can provide a `content_type` for the email and specify `text/plain` or `text/html` to be sent.
  18. If you do not specify `content_type`, then the recipient email server will determine the correct rendering.
  19. Set `expected_receive_period_in_days` to the maximum amount of time that you'd expect to pass between Events being received by this Agent.
  20. MD
  21. def default_options
  22. {
  23. 'subject' => "You have some notifications!",
  24. 'headline' => "Your notifications:",
  25. 'expected_receive_period_in_days' => "2"
  26. }
  27. end
  28. def working?
  29. received_event_without_error?
  30. end
  31. def receive(incoming_events)
  32. self.memory['events'] ||= []
  33. incoming_events.each do |event|
  34. self.memory['events'] << event.id
  35. end
  36. end
  37. def check
  38. if self.memory['events'] && self.memory['events'].length > 0
  39. payloads = received_events.reorder("events.id ASC").where(id: self.memory['events']).pluck(:payload).to_a
  40. groups = payloads.map { |payload| present(payload) }
  41. recipients.each do |recipient|
  42. SystemMailer.send_message(
  43. to: recipient,
  44. from: interpolated['from'],
  45. subject: interpolated['subject'],
  46. headline: interpolated['headline'],
  47. content_type: interpolated['content_type'],
  48. groups:
  49. ).deliver_now
  50. log "Sent digest mail to #{recipient}"
  51. rescue StandardError => e
  52. error("Error sending digest mail to #{recipient}: #{e.message}")
  53. raise
  54. end
  55. self.memory['events'] = []
  56. end
  57. end
  58. end
  59. end