memEx/lib/memex/accounts/email.ex

62 lines
2.1 KiB
Elixir
Raw Normal View History

2022-07-25 19:31:54 -04:00
defmodule Memex.Email do
2022-02-25 21:35:12 -05:00
@moduledoc """
Emails that can be sent using Swoosh.
You can find the base email templates at
2023-04-13 23:48:17 -04:00
`lib/memex_web/components/layouts/email_html.html.heex` for html emails and
`lib/memex_web/components/layouts/email_text.txt.eex` for text emails.
2022-02-25 21:35:12 -05:00
"""
2023-04-13 23:29:29 -04:00
import Swoosh.Email
2022-07-25 19:31:54 -04:00
import MemexWeb.Gettext
2023-04-13 23:29:29 -04:00
import Phoenix.Template
2022-07-25 19:31:54 -04:00
alias Memex.Accounts.User
2023-04-13 23:29:29 -04:00
alias MemexWeb.{EmailHTML, Layouts}
2022-02-25 21:35:12 -05:00
@typedoc """
Represents an HTML and text body email that can be sent
"""
@type t() :: Swoosh.Email.t()
@spec base_email(User.t(), String.t()) :: t()
defp base_email(%User{email: email}, subject) do
2022-11-27 12:03:51 -05:00
from = Application.get_env(:memex, Memex.Mailer)[:email_from] || "noreply@localhost"
name = Application.get_env(:memex, Memex.Mailer)[:email_name]
2022-02-25 21:35:12 -05:00
new() |> to(email) |> from({name, from}) |> subject(subject)
end
@spec generate_email(key :: String.t(), User.t(), attrs :: map()) :: t()
def generate_email("welcome", user, %{"url" => url}) do
user
2022-07-25 19:31:54 -04:00
|> base_email(dgettext("emails", "Confirm your Memex account"))
2023-04-13 23:29:29 -04:00
|> html_email(:confirm_email_html, %{user: user, url: url})
|> text_email(:confirm_email_text, %{user: user, url: url})
2022-02-25 21:35:12 -05:00
end
def generate_email("reset_password", user, %{"url" => url}) do
user
2022-07-25 19:31:54 -04:00
|> base_email(dgettext("emails", "Reset your Memex password"))
2023-04-13 23:29:29 -04:00
|> html_email(:reset_password_html, %{user: user, url: url})
|> text_email(:reset_password_text, %{user: user, url: url})
2022-02-25 21:35:12 -05:00
end
def generate_email("update_email", user, %{"url" => url}) do
user
2022-07-25 19:31:54 -04:00
|> base_email(dgettext("emails", "Update your Memex email"))
2023-04-13 23:29:29 -04:00
|> html_email(:update_email_html, %{user: user, url: url})
|> text_email(:update_email_text, %{user: user, url: url})
end
defp html_email(email, atom, assigns) do
heex = apply(EmailHTML, atom, [assigns])
html = render_to_string(Layouts, "email_html", "html", email: email, inner_content: heex)
email |> html_body(html)
end
defp text_email(email, atom, assigns) do
heex = apply(EmailHTML, atom, [assigns])
text = render_to_string(Layouts, "email_text", "text", email: email, inner_content: heex)
email |> text_body(text)
2022-02-25 21:35:12 -05:00
end
end