SendGrid and Phoenix Framework

This is a small tutorial explaining how to use SendGrid to send emails in Phoenix Framework (1.4)

We need to start by adding Bamboo to mix.exs dependencies:

Add to defp deps do list

{:bamboo, "~> 1.2"}, {:poison, "~> 4.0"}

Then in your config.exs add the following lines:

config :my_app, MyProject.Mail, adapter: Bamboo.SendGridAdapter, api_key: System.get_env("SENDGRID_API_KEY")

:my_app should be the same atom being used in the other configurations in this file.

MyProject.Mail should be a module defined by use that will handle all the sending of emails.

I’m using environment variables to allow for the configuration to be more dynamic, specially between environments (dev, staging, production, etc)

To define the environment variable just define in the terminal:

export SENDGRID_API_KEY=you-key-here This way Phoenix can pick it up at runtime, using `System.get_env`.

After this we need to create our module that is going to handle the sending of emails from our project.

Lets create a file called lib/my_project/mail.ex and add:

defmodule MyProject.Mail do
  use Bamboo.Mailer, otp_app: :my_app

  import Bamboo.SendGridHelper
  import Bamboo.Email

  def send_notification_email(email, hash) do
    html = """
    <html>
    <head>
    <title>%PRODUCT% - %TITLE%</title>
    <link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
    </head>
    <body>
    <div class="container">
    <div class="row">
      <div class="column">
        <h3>%TITLE%</h3>
      </div>
    </div>
    <div class="row">
      <div class="column">
        <p><strong><a href="%HOST%/%URL%" class="button">CONFIRM MY EMAIL ADDRESS</a></strong></p>

      </div>
    </div>
    </body>
    </html>
    """

    title = "Finish creating your account"

    new_email()
    |> to(email)
    |> subject("Email Confirmation")
    |> substitute("%HOST%", @host)
    |> substitute("%TITLE%", title)
    |> html_body(html)
    |> deliver_now()
  end

end
Pedro Luz
A personal blog by Pedro Luz about coding, coding, habit building, and a few things more.(Psst... I am open to opportunities.)
Reach out to me on your favorite social :)© 2020 Pedro Luz