memEx/lib/memex/email.ex

57 lines
2.0 KiB
Elixir
Raw Permalink 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
2023-04-14 18:29:34 -04:00
|> base_email(dgettext("emails", "confirm your memEx account"))
2023-04-14 19:02:06 -04:00
|> render_body(:confirm_email, %{user: user, url: url})
2022-02-25 21:35:12 -05:00
end
def generate_email("reset_password", user, %{"url" => url}) do
user
2023-04-14 18:29:34 -04:00
|> base_email(dgettext("emails", "reset your memEx password"))
2023-04-14 19:02:06 -04:00
|> render_body(:reset_password, %{user: user, url: url})
2022-02-25 21:35:12 -05:00
end
def generate_email("update_email", user, %{"url" => url}) do
user
2023-04-14 18:29:34 -04:00
|> base_email(dgettext("emails", "update your memEx email"))
2023-04-14 19:02:06 -04:00
|> render_body(:update_email, %{user: user, url: url})
2023-04-13 23:29:29 -04:00
end
2023-04-14 19:02:06 -04:00
defp render_body(email, template, assigns) do
html_heex = apply(EmailHTML, String.to_existing_atom("#{template}_html"), [assigns])
html = render_to_string(Layouts, "email_html", "html", email: email, inner_content: html_heex)
text_heex = apply(EmailHTML, String.to_existing_atom("#{template}_text"), [assigns])
text = render_to_string(Layouts, "email_text", "text", email: email, inner_content: text_heex)
2023-04-13 23:29:29 -04:00
2023-04-14 19:02:06 -04:00
email |> html_body(html) |> text_body(text)
2022-02-25 21:35:12 -05:00
end
end