email_agent.rb 2.8 KB

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