akkoma/lib/pleroma/emails/mailer.ex

72 lines
1.9 KiB
Elixir
Raw Normal View History

# Pleroma: A lightweight social networking server
2018-12-31 15:41:47 +00:00
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Emails.Mailer do
@moduledoc """
Defines the Pleroma mailer.
2019-02-20 16:51:25 +00:00
The module contains functions to delivery email using Swoosh.Mailer.
"""
alias Pleroma.Repo
alias Pleroma.Workers.MailerWorker
alias Swoosh.DeliveryError
@otp_app :pleroma
@mailer_config [otp: :pleroma]
@spec enabled?() :: boolean()
def enabled?, do: Pleroma.Config.get([__MODULE__, :enabled])
import Pleroma.Workers.WorkerHelper, only: [worker_args: 1]
@doc "add email to queue"
2019-02-20 16:51:25 +00:00
def deliver_async(email, config \\ []) do
encoded_email =
email
|> :erlang.term_to_binary()
|> Base.encode64()
%{"op" => "email", "encoded_email" => encoded_email, "config" => config}
|> MailerWorker.new(worker_args(:mailer))
|> Repo.insert()
2019-02-20 16:51:25 +00:00
end
@doc "callback to perform send email from queue"
2019-02-20 16:51:25 +00:00
def perform(:deliver_async, email, config), do: deliver(email, config)
@spec deliver(Swoosh.Email.t(), Keyword.t()) :: {:ok, term} | {:error, term}
def deliver(email, config \\ [])
def deliver(email, config) do
case enabled?() do
true -> Swoosh.Mailer.deliver(email, parse_config(config))
false -> {:error, :deliveries_disabled}
end
end
@spec deliver!(Swoosh.Email.t(), Keyword.t()) :: term | no_return
def deliver!(email, config \\ [])
def deliver!(email, config) do
case deliver(email, config) do
{:ok, result} -> result
{:error, reason} -> raise DeliveryError, reason: reason
end
end
@on_load :validate_dependency
@doc false
def validate_dependency do
parse_config([])
|> Keyword.get(:adapter)
|> Swoosh.Mailer.validate_dependency()
end
defp parse_config(config) do
Swoosh.Mailer.parse_config(@otp_app, __MODULE__, @mailer_config, config)
end
2018-12-10 17:20:50 +00:00
end