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

Phoenix is a popular web framework known for its speed, reliability, and scalability. One of its key features is its ability to handle requests and send emails efficiently. In this article, we’ll explore how to send emails using Phoenix Swoosh, a powerful email library.

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:

“`

Welcome, <%= @name %>

We’re excited to have you on board!

“`

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:

“`




Thanks for signing up!

“`

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

Your email address will not be published. Required fields are marked *