/
swoosh.ex
73 lines (60 loc) · 2.03 KB
/
swoosh.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
if Code.ensure_loaded?(Swoosh) do
defmodule BoomNotifier.MailNotifier.Swoosh do
@moduledoc """
Send exception notification by email using `Swoosh`.
## Usage
```elixir
defmodule YourApp.Router do
use Phoenix.Router
use BoomNotifier,
notifier: BoomNotifier.MailNotifier.Swoosh,
options: [
mailer: YourApp.Mailer,
from: "me@example.com",
to: "foo@example.com",
subject: "BOOM error caught"
]
# ...
```
"""
@behaviour BoomNotifier.Notifier
import Swoosh.Email
alias BoomNotifier.ErrorInfo
alias BoomNotifier.MailNotifier
alias BoomNotifier.MailNotifier.HTMLContent
alias BoomNotifier.MailNotifier.TextContent
@type option ::
{:mailer, module()} | {:from, String.t()} | {:to, String.t()} | {:subject, String.t()}
@type options :: [option]
@impl BoomNotifier.Notifier
defdelegate validate_config(options), to: MailNotifier
@impl BoomNotifier.Notifier
@spec notify(ErrorInfo.t(), options) :: no_return()
def notify(error_info, options) do
# Note, unlike Bamboo, Swoosh will raise while creating the mail if it is
# invalid (has a bad recipient, etc).
# To consumers of this function, the behaviour is identical to Bamboo's
# `deliver_later!` because we dispatch the mail in a task.
subject =
MailNotifier.build_subject(
options[:subject],
error_info,
options[:max_subject_length] || 80
)
email =
new()
|> to(options[:to])
|> from(options[:from])
|> subject(subject)
|> html_body(HTMLContent.build(error_info))
|> text_body(TextContent.build(error_info))
# Swoosh does not provide async send, but it recommends using Elixir tasks.
# This is actually identical to Bamboo, Bamboo just wraps the boiler plate.
Task.start(fn ->
options[:mailer].deliver!(email)
end)
# return email to mirror bamboo deliver_later!
email
end
end
end