email_agent.rb 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. require 'net/smtp'
  2. module Agents
  3. class EmailAgent < Agent
  4. include EmailConcern
  5. can_dry_run!
  6. default_schedule "never"
  7. cannot_create_events!
  8. no_bulk_receive!
  9. description <<~MD
  10. The Email Agent sends any events it receives via email immediately.
  11. You can specify the email's subject line by providing a `subject` option, which can contain [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) formatting. E.g.,
  12. you could provide `"Huginn email"` to set a simple subject, or `{{subject}}` to use the `subject` key from the incoming Event.
  13. By default, the email body will contain an optional `headline`, followed by a listing of the Events' keys.
  14. You can customize the email body by including the optional `body` param. Like the `subject`, the `body` can be a simple message
  15. or a Liquid template. You could send only the Event's `some_text` field with a `body` set to `{{ some_text }}`.
  16. The body can contain simple HTML and will be sanitized. Note that when using `body`, it will be wrapped with `<html>` and `<body>` tags,
  17. so you do not need to add these yourself.
  18. You can specify one or more `recipients` for the email, or skip the option in order to send the email to your
  19. account's default email address.
  20. 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']}`).
  21. You can provide a `content_type` for the email and specify `text/plain` or `text/html` to be sent.
  22. If you do not specify `content_type`, then the recipient email server will determine the correct rendering.
  23. 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.
  24. MD
  25. def default_options
  26. {
  27. 'subject' => "You have a notification!",
  28. 'headline' => "Your notification:",
  29. 'expected_receive_period_in_days' => "2"
  30. }
  31. end
  32. def working?
  33. received_event_without_error?
  34. end
  35. def receive(incoming_events)
  36. incoming_events.each do |event|
  37. recipients(event.payload).each do |recipient|
  38. SystemMailer.send_message(
  39. to: recipient,
  40. from: interpolated(event)['from'],
  41. subject: interpolated(event)['subject'],
  42. headline: interpolated(event)['headline'],
  43. body: interpolated(event)['body'],
  44. content_type: interpolated(event)['content_type'],
  45. groups: [present(event.payload)]
  46. ).deliver_now
  47. log "Sent mail to #{recipient} with event #{event.id}"
  48. rescue StandardError => e
  49. error("Error sending mail to #{recipient} with event #{event.id}: #{e.message}")
  50. raise
  51. end
  52. end
  53. end
  54. end
  55. end