# Sending email with Swoosh

[Swoosh](https://hex.pm/packages/swoosh) builds and delivers emails; Braces writes their
bodies. This guide's examples are Handlebars, and the same works with the other languages'
modules, such as `Braces.Liquid.render/3` and `Braces.Jinja.render/3`. It covers both kinds of
email template:

- **Templates in your code**, compiled with your app: transactional emails such as a welcome
  or a password reset.
- **Templates in your data**, written by your users or your marketing team and rendered at
  runtime, such as templates moved from SendGrid, Postmark or Mailchimp.

Neither needs Phoenix.

HTML email is written in [MJML](https://mjml.io), which compiles to HTML that email clients
render alike, with the [`mjml`](https://hex.pm/packages/mjml) package. Handlebars fills in the
MJML, then MJML turns it into HTML.

```elixir
# mix.exs
def deps do
  [
    {:braces, "~> 0.1"},
    {:swoosh, "~> 1.17"},
    {:mjml, "~> 5.0"}
  ]
end
```

## Templates in your code

Keep each email's MJML and text bodies in `.hbs` files beside the module that sends it:

```
lib/my_app/
├── user_email.ex
└── user_email/
    ├── welcome.mjml.hbs
    ├── welcome.text.hbs
    └── partials/
        ├── layout.hbs
        └── footer.hbs
```

`Braces.Handlebars.embed_templates/2` names each function after its file up to the first dot, so
`welcome.mjml.hbs` and `welcome.text.hbs` would both be `welcome`. Embed each format in its own
module, and build the email in a third:

```elixir
defmodule MyApp.UserEmail.MJML do
  use Braces.Handlebars, helpers: MyApp.EmailHelpers, partials: "user_email/partials/*.hbs"

  embed_templates "user_email/*.mjml.hbs"
end

defmodule MyApp.UserEmail.Text do
  use Braces.Handlebars, helpers: MyApp.EmailHelpers

  embed_templates "user_email/*.text.hbs"
end

defmodule MyApp.UserEmail do
  import Swoosh.Email
  alias MyApp.UserEmail.{MJML, Text}

  def welcome(user, confirm_url) do
    assigns = %{user: user, confirm_url: confirm_url}

    new()
    |> to({user.name, user.email})
    |> from({"MyApp", "hello@example.com"})
    |> subject("Welcome, #{user.name}!")
    |> html_body(assigns |> MJML.welcome() |> to_html!())
    |> text_body(assigns |> Text.welcome(no_escape: true) |> IO.iodata_to_binary())
  end

  defp to_html!(mjml) do
    {:ok, html} = mjml |> IO.iodata_to_binary() |> Mjml.to_html()
    html
  end
end
```

```elixir
user |> MyApp.UserEmail.welcome(url) |> MyApp.Mailer.deliver()
```

- The embedded functions return iodata. `Mjml.to_html/2` and Swoosh's adapters take strings,
  so convert with `IO.iodata_to_binary/1`.
- MJML is markup, so values are escaped in it as in HTML: `Ada & Co` is `Ada &amp; Co`, and
  MJML keeps it so in the HTML. A value can't add MJML tags to your email.
- Render the text body with `no_escape: true`: it isn't markup, so `Ada & Co` must stay
  `Ada & Co`.
- They render in strict mode: a value the template uses that isn't in `assigns` raises a
  `Braces.Handlebars.RenderError`, so a typo can't send an email that says "Hi !". Pass
  `strict: false` to render it as empty instead.
- Data can be maps with atom or string keys, or structs: `{{user.name}}` reads the `name` field
  of a `%User{}`.

### A layout

A layout is a partial that renders the email's content where it says
`{{> @partial-block}}`. Here it also renders a `preview` partial, the text that inboxes show
after the subject, which each email defines with `{{#*inline}}`:

```handlebars
{{! user_email/partials/layout.hbs }}
<mjml>
  <mj-head>
    <mj-preview>{{> preview}}</mj-preview>
  </mj-head>
  <mj-body>
    <mj-section>
      <mj-column>
        {{> @partial-block}}
        {{> footer}}
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>
```

```handlebars
{{! user_email/partials/footer.hbs }}
<mj-text font-size="12px" color="#888">Sent to {{user.email}}</mj-text>
```

```handlebars
{{! user_email/welcome.mjml.hbs }}
{{#> layout}}
  {{#*inline "preview"}}Confirm your account, {{user.name}}{{/inline}}
  <mj-text font-size="20px">Hi {{user.name}}!</mj-text>
  {{#button confirm_url}}Confirm your account{{/button}}
{{/layout}}
```

The layout may call `preview` because a template of the module defines it. Which template
renders the layout is only known as it renders, so an email that doesn't define `preview`
compiles, and raises when it's rendered:

```
** (Braces.Handlebars.RenderError) The partial preview could not be found - 3:16 in partial layout

        <mj-preview>{{> preview}}</mj-preview>
                    ^
```

A test that renders each email catches it (see [Testing](#testing)).

### Helpers

Helpers are the public functions of a module that uses `Braces.Handlebars.Helpers` (see
[Helpers and partials](helpers-and-partials.md)):

```elixir
defmodule MyApp.EmailHelpers do
  use Braces.Handlebars.Helpers

  # {{#button confirm_url}}Confirm your account{{/button}}
  def button(url, options) do
    Braces.Handlebars.safe(
      ~s(<mj-button href="#{Braces.Handlebars.escape(url)}">#{options.fn.(options.this)}</mj-button>)
    )
  end

  # {{money order.total_cents}}
  def money(cents, _options), do: "$" <> :erlang.float_to_binary(cents / 100, decimals: 2)
end
```

A helper that builds markup escapes what it puts in it with `Braces.Handlebars.escape/1`, and returns
`Braces.Handlebars.safe/1` so the markup isn't escaped again. `options.fn` gives the block's text,
already escaped.

Since the helpers and partials are compiled with the templates, a template that calls one that
doesn't exist, such as `{{#buton url}}`, fails the build instead of the delivery (see
[Compiled templates](compiled-templates.md#helpers-and-partials)).

### Why not Phoenix templates

Phoenix's `.hbs` templates (see [the Phoenix guide](phoenix.md)) escape values only in HTML
formats, so a `welcome.mjml.hbs` Phoenix template would write values unescaped. They also have
no custom helpers or partials. Use the modules above for email.

## Templates in your data

Templates that people edit at runtime are parsed with `Braces.Handlebars.compile/2` and rendered with
`Braces.Handlebars.render_to_string/3`. Parsing reads the template without generating code or
creating atoms, so it is safe for templates you don't control.

```elixir
defmodule MyApp.Campaigns do
  import Swoosh.Email
  import Braces.Handlebars.Sigil

  @partials %{
    "footer" =>
      ~HBS"""
      <mj-text>Sent to {{email}}. <a href="{{unsubscribe_url}}">Unsubscribe</a></mj-text>
      """
  }

  def build(%MyApp.Campaigns.Template{} = template, recipient) do
    data = %{
      "first_name" => recipient.first_name,
      "email" => recipient.email,
      "unsubscribe_url" => MyApp.unsubscribe_url(recipient)
    }

    with {:ok, subject} <- render(template.subject, data, no_escape: true),
         {:ok, mjml} <- render(template.mjml_body, data, []),
         {:ok, html} <- Mjml.to_html(mjml),
         {:ok, text} <- render(template.text_body, data, no_escape: true) do
      {:ok,
       new()
       |> to({recipient.name, recipient.email})
       |> from({"MyApp", "news@example.com"})
       |> subject(subject)
       |> html_body(html)
       |> text_body(text)}
    end
  end

  defp render(source, data, opts) do
    with {:ok, template} <- Braces.Handlebars.compile(source) do
      Braces.Handlebars.render_to_string(template, data,
        [helpers: MyApp.EmailHelpers, partials: @partials] ++ opts
      )
    end
  end
end
```

- The subject is a template too, rendered with `no_escape: true` like the text body.
- `build/2` returns `{:error, %Braces.Handlebars.ParseError{}}` or
  `{:error, %Braces.Handlebars.RenderError{}}`, with the line and a caret in `error.message`, or
  MJML's `{:error, message}`, rather than raising in the middle of a send.
- The footer partial is a `~HBS` template, parsed and checked when the module compiles
  (see [Partials](helpers-and-partials.md#partials)).
- Runtime templates get the same helpers module as compiled ones, so your users can call
  `{{#button url}}` and `{{money total}}`.
- Sending one template to many recipients? Compile it once with `Braces.Handlebars.compile/2` and
  render that `Braces.Handlebars.Template` for each recipient.

Reject a template that doesn't parse, or whose MJML body writes a value without escaping, when
it's saved, and let its author preview it as they type: see
[Validating on save](phoenix.md#validating-on-save) and
[Previewing in a LiveView](phoenix.md#previewing-in-a-liveview) in the Phoenix guide, and
[Security](security.md).

### Data from JSON

When recipient data arrives as JSON, such as from a webhook or a provider export, decode it
with `Braces.Handlebars.decode_json/1`. It keeps each object's keys in their order, so `{{#each}}`
over an object walks them as Handlebars.js does:

```elixir
{:ok, data} = Braces.Handlebars.decode_json(payload)
Braces.Handlebars.render_to_string(template, data)
```

### Templates in other languages

Templates from a provider that uses Liquid, such as Shopify or Braze, render with
`Braces.Liquid.render/3`. A template in any language Braces reads converts to the language you
keep your templates in with `Braces.convert/2`:

```elixir
{:ok, source} = Braces.convert(liquid, from: :liquid, to: :handlebars)
```

See the [Conversions](conversions.md) guide.

## Testing

Configure the test adapter in `config/test.exs`:

```elixir
config :my_app, MyApp.Mailer, adapter: Swoosh.Adapters.Test
```

Then assert on what was rendered:

```elixir
defmodule MyApp.UserEmailTest do
  use ExUnit.Case, async: true
  import Swoosh.TestAssertions

  test "welcome escapes the name in HTML, not in text" do
    user = %{name: "Ada & Co", email: "ada@example.com"}

    email = MyApp.UserEmail.welcome(user, "https://example.com/confirm")

    assert email.html_body =~ "Hi Ada &amp; Co!"
    assert email.text_body =~ "Hi Ada & Co!"

    MyApp.Mailer.deliver(email)
    assert_email_sent(subject: "Welcome, Ada & Co!")
  end
end
```

Since compiled templates fail the build when they call a helper or partial that doesn't exist,
the tests only need to check what the email says.
