revert 4a94c9a31ef11f63ea71ad9c1f085c18cf8ef083
[akkoma] / lib / pleroma / emails / mailer.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Emails.Mailer do
6 @moduledoc """
7 Defines the Pleroma mailer.
8
9 The module contains functions to delivery email using Swoosh.Mailer.
10 """
11
12 alias Pleroma.Workers.MailerWorker
13 alias Swoosh.DeliveryError
14
15 @otp_app :pleroma
16 @mailer_config [otp: :pleroma]
17
18 @spec enabled?() :: boolean()
19 def enabled?, do: Pleroma.Config.get([__MODULE__, :enabled])
20
21 @doc "add email to queue"
22 def deliver_async(email, config \\ []) do
23 encoded_email =
24 email
25 |> :erlang.term_to_binary()
26 |> Base.encode64()
27
28 MailerWorker.enqueue("email", %{"encoded_email" => encoded_email, "config" => config})
29 end
30
31 @doc "callback to perform send email from queue"
32 def perform(:deliver_async, email, config), do: deliver(email, config)
33
34 @spec deliver(Swoosh.Email.t(), Keyword.t()) :: {:ok, term} | {:error, term}
35 def deliver(email, config \\ [])
36
37 def deliver(email, config) do
38 # temporary hackney fix until hackney max_connections bug is fixed
39 # https://git.pleroma.social/pleroma/pleroma/-/issues/2101
40 email =
41 Swoosh.Email.put_private(email, :hackney_options, ssl_options: [versions: [:"tlsv1.2"]])
42
43 case enabled?() do
44 true -> Swoosh.Mailer.deliver(email, parse_config(config))
45 false -> {:error, :deliveries_disabled}
46 end
47 end
48
49 @spec deliver!(Swoosh.Email.t(), Keyword.t()) :: term | no_return
50 def deliver!(email, config \\ [])
51
52 def deliver!(email, config) do
53 case deliver(email, config) do
54 {:ok, result} -> result
55 {:error, reason} -> raise DeliveryError, reason: reason
56 end
57 end
58
59 @on_load :validate_dependency
60
61 @doc false
62 def validate_dependency do
63 parse_config([])
64 |> Keyword.get(:adapter)
65 |> Swoosh.Mailer.validate_dependency()
66 end
67
68 defp parse_config(config) do
69 Swoosh.Mailer.parse_config(@otp_app, __MODULE__, @mailer_config, config)
70 end
71 end