The Elixir ecosystem is rich with libraries offering us the ability to send emails such as Swoosh and Bamboo. For our application we'll be using Bamboo by Thoughtbot which has support for composable emails and many different email providers. Bamboo also has really good documentation that's worth looking over.
Sending emails is one of the ways we see Elixir sets itself apart from other languages like Ruby. With great support for concurrency we won't need to include other dependencies to enable our applications to send emails in the background.
The first thing we need to do is add our newest dependency, :bamboo to our mix.exs file:
... defp deps do [ {:bamboo, "~> 0.7"}, ... ] end...Next we need to add :bamboo to our application function in mix.exs:
def application do [mod: {PhoenixChat, []}, applications: [ :bamboo, ... ]]endThen be sure to get your dependencies.
$ mix deps.getOne of the best features of Bamboo is its support for different providers. For our project we'll be using Mailgun but if you have a strong preference for another provider, the configuration should be similar.
Let's open up config/dev.exs and add a section for Bamboo at the bottom. This configuration will be used only in development mode and informs Bamboo as to which adapter or provider to use:
config :phoenix_chat, PhoenixChat.Mailer, adapter: Bamboo.LocalAdapterThe Bamboo.LocalAdapter is great for development. Rather than sending emails over the network and through our providers, the emails are captured locally and available for previewing.
The other configurations need to be updated to include an appropriate Bamboo config. For testing we'll want to use the special Bamboo.TestAdapter, which handles email in memory and does not send emails, and in production we'll use the Bamboo.MailgunAdapter.
For a complete list of adapters see the Bamboo docs: Adapters.
Open config/test.exs and add the following:
config :phoenix_chat, PhoenixChat.Mailer, adapter: Bamboo.TestAdapterFor the production configuration we'll use Mailgun and pull the API key and Mailgun domain from our system environment variables, which we will define later:
config :phoenix_chat, PhoenixChat.Mailer, adapter: Bamboo.MailgunAdapter, api_key: System.get_env("MAILGUN_API_KEY"), domain: System.get_env("MAILGUN_DOMAIN")Now that we've installed Bamboo and configured it, we need to create our Mailer and define our emails.
Create a new file, lib/phoenix_chat/mailer.ex, so we can define our Mailer module:
$ touch lib/phoenix_chat/mailer.exdefmodule PhoenixChat.Mailer do use Bamboo.Mailer, otp_app: :phoenix_chatendThe Mailer is used for dispatching the emails to the adapter but construction of the Emails is done elsewhere. Let's create an Email module lib/phoenix_chat/email.ex to construct our emails.
Phoenix is not necessary to use Bamboo, but we can use the special adapter to make email formatting easier down the road. It also comes with this handy tool for previewing formatted emails. If you don't need formatted emails, you can simply use import Bamboo.Email rather than Bamboo.Phoenix.
$ touch lib/phoenix_chat/email.exdefmodule PhoenixChat.Email do use Bamboo.Phoenix, view: PhoenixChat.EmailViewendNext we'll need to create our first email. In Bamboo, emails are defined as functions and are built up using a helpful domain-specific language (DSL). If you're not familiar with DSLs, you can think of them as tiny, special-purpose languages or libraries that are really good at doing one thing--in this case, email.
To get started, we'll define a basic welcome email:
defmodule PhoenixChat.Email do use Bamboo.Phoenix, view: PhoenixChat.EmailView alias PhoenixChat.{User} def welcome_email(%User{email: email}) do new_email |> to(email) |> from("no-reply@phoenixchat.io") |> subject("Welcome") |> text_body("Welcome to PhoenixChat!") endendBamboo's API is pretty easy. As you can see in the above code we specify the email to send to, the from address, subject, and then the text body.
That's it for creating an email, now we need to send it.
With Bamboo there are two ways to send emails within the current request and in the background. To send an email within the current request, we use the deliver_now/1 function on our mailer. This function will dispatch the email request immediately and will need a response before the HTTP request can continue.
alias PhoenixChat.{Email, Mailer}user |> Email.welcome_email |> Mailer.deliver_nowTo send our emails in the background we can use the deliver_later/1 function in Bamboo:
user |> Email.welcome_email |> Mailer.deliver_laterThe advantage of sending in the background is we won't block the current request, this has the least impact on the user's experience and it's what we will use almost exclusively.
With our emails created and configured, we can proceed with integrating the welcome email into Phoenix. Let's start by opening web/controller/user_controller.ex and creating a new method, send_welcome_email/, to handle sending the email.
alias PhoenixChat.{Email, Mailer, User} ... defp send_welcome_email(user) do user |> Email.welcome_email |> Mailer.deliver_later end...Once we've created our function we can incorporate it into create/2, which is the function that gets called when we create a new user.
... def create(conn, %{"user" => user_params}) do changeset = User.registration_changeset(%User{}, user_params) case Repo.insert(changeset) do {:ok, user} -> {:ok, token, _claims} = Guardian.encode_and_sign(user, :token) send_welcome_email(user) ... end endThat's it! Now our users will receive a simple welcome email when they register for a new account. If you sign up, you should see something along the lines of the following in your server logs.
%Bamboo.Email{assigns: %{}, bcc: [], cc: [],from: {nil, "no-reply@phoenixchat.io"}, headers: %{},html_body: nil, private: %{}, subject: "Welcome",text_body: "Welcome to PhoenixChat!",to: [nil: "info@learnphoenix.io"]}