Sending Emails with Phoenix Swoosh: A Step-by-Step Guide

Setting up a Phoenix Project

To start, let’s create a new Phoenix project. We’ll use SQLite as our database to keep things simple. Run the following command in your terminal:

mix phx.new hello --database sqlite

Next, add the phoenix_swoosh dependency to your mix.exs file:

defp deps do
  [
    #...
    {:phoenix_swoosh, "~> 1.3"}
  ]
end

Email Styling

When sending emails, it’s essential to consider styling to make them visually appealing. We can use HTML templates to achieve this. Create a new file welcome.html.eex in the lib/hello_web/templates/emails/welcome directory:

<p>
  Welcome, <%= @name %>
</p>

<p>
  We're excited to have you on board!
</p>

Setting up Email Templates

Create a new file user_email.ex in the lib directory:

defmodule Hello.UserEmail do
  use Swoosh.Email

  def welcome(name, email) do
    new()
    |> to(email)
    |> from("[email protected]")
    |> subject("Welcome to Hello!")
    |> render_body("welcome.html", %{name: name})
  end
end

Setting up the Controller

Create a new file page_controller.ex in the lib/hello_web/controllers directory:

defmodule Hello.PageController do
  use HelloWeb, :controller

  def signup(conn, %{"name" => name, "email" => email}) do
    email = UserEmail.welcome(name, email)
    Mailer.deliver(email)

    conn
    |> put_flash(:info, "Thanks for signing up!")
    |> render("thanks.html")
  end
end

Creating HTML Pages

Create two new files index.html.heex and thanks.html.heex in the lib/hello_web/templates/page directory:

<form>
  <label>Name:</label>
  <input type="text" name="name">
  <br>
  <label>Email:</label>
  <input type="email" name="email">
  <br>
  <button type="submit">Sign up</button>
</form>
<p>Thanks for signing up!</p>

Inspecting Generated Emails

By default, Swoosh sends emails to a development mailbox. You can view sent emails at http://localhost:4000/dev/mailbox.

That’s it! With these steps, you’ve successfully set up email sending with Phoenix Swoosh. Remember to configure your email systems in the prod.exs file and keep secrets out of source control.

Leave a Reply