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
1
2
|
{:bamboo, "~> 1.2"},
{:poison, "~> 4.0"}
|
Then in your config.exs
add the following lines:
100
101
102
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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
|