Phoenix.Swoosh
This module provides the ability to set the HTML and/or text body of an email by rendering templates.
Installation
Add :phoenix_swoosh to your list of dependencies in mix.exs:
def deps do
[
{:phoenix_swoosh, "~> 1.0"}
]
endUsage
1. Classic setup
Setting up the templates:
# path_to/templates/user_notifier/welcome.html.eex
<div>
<h1>Welcome to Sample, <%= @name %>!</h1>
</div>defmodule Sample.UserNotifierView do
use Phoenix.View, root: "path_to/templates"
endPassing values to templates:
# path_to/notifiers/user_notifier.ex
defmodule Sample.UserNotifier do
use Phoenix.Swoosh, view: Sample.UserNotifierView
def welcome(user) do
new()
|> from("tony@stark.com")
|> to(user.email)
|> subject("Hello, Avengers!")
|> render_body("welcome.html", %{name: name})
end
endMaybe with a layout:
# path_to/templates/layout/email.html.eex
<html>
<head>
<title><%= @email.subject %></title>
</head>
<body>
<%= @inner_content %>
</body>
</html>defmodule Sample.LayoutView do
use Phoenix.View, root: "path_to/templates"
end# path_to/notifiers/user_notifier.ex
defmodule Sample.UserNotifier do
use Phoenix.Swoosh, view: Sample.NotifierView, layout: {Sample.LayoutView, :email}
# ... same welcome ...
endLayout can also be added/changed dynamically with put_new_layout/2 and put_layout/2
2. Standalone setup
# path_to/templates/user_notifier/welcome.html.eex
<div>
<h1>Welcome to Sample, <%= @name %>!</h1>
</div># path_to/notifiers/user_notifier.ex
defmodule Sample.UserNotifier do
use Phoenix.Swoosh, template_root: "path_to/templates", template_path: "user_notifier"
# ... same welcome ...
endIn this setup, the notifier module itself serves as the view module
template_root, template_path and template_namespace
will be passed to Phoenix.View as root, path and namespace.
Layout can be setup the same way as classic setup.
Copyright and License
Copyright (c) 2021 Swoosh contributors
Released under the MIT License, which can be found in LICENSE.md.