Sending Email With SendGrid and Elixir

SendGrid is an email service that allows you to send both transactional email and newsletter email from a single platform along with many other niceties. Setting up your Elixir projects to take advantage of platform is quite easy with my sendgrid library.

Add The Dependency

Add the :sendgrid dependency to your list of dependencies in your mix.exs file:

{:sendgrid, "~> 0.0.2"}

Add Your SendGrid API Key

Update your config.exs to include your SendGrid API key:

config :sendgrid,
  api_key: "SENDGRID_API_KEY"

Using The Library

Once you've added the dependency and added your API, you're ready to start sending some emails. The basic structure you'll be using is %SendGrid.Email and build it in a composable way and sending individual emails with the SendGrid.Mailer module.

For example, here's how you can send an email with HTML content:

alias SendGrid.{Mailer, Email}

email = 
  Email.build()
  |> Email.put_from("test@email.com")
  |> Email.put_to("test2@email.com")
  |> Email.put_subject("Hello From Elixir")
  |> Email.put_html("<html><body><p>Sent from Elixir!</p></body></html>")

Mailer.send(email)

Simple, right?

Here's how you can send an email with Text context:

alias SendGrid.{Mailer, Email}

email = 
  Email.build()
  |> Email.put_from("test@email.com")
  |> Email.put_to("test2@email.com")
  |> Email.put_subject("Hello From Elixir")
  |> Email.put_text("Sent from Elixir!")

Mailer.send(email)

If you need to use your predefined templates and substitute in dynamic values, the library has you covered:

alias SendGrid.{Mailer, Email}

email = 
  Email.build()
  |> Email.put_template("the_template_id")
  |> Email.add_substitution("-foo-", "bar")
  |> Email.put_html("<span>Some Text</span>")

Mailer.send(email)

Check out the docs to explore the full functionality of the library.

Questions Or Suggestions?

Please feel to leave me feedback or ask questions so I can make this library better for everyone.

#elixir   •   #sendgrid