Skip to content

Instantly share code, notes, and snippets.

@mlankenau
Created November 5, 2018 12:48
Show Gist options
  • Save mlankenau/91d450f6ad9edb3cbadbd9aa746b176f to your computer and use it in GitHub Desktop.
Save mlankenau/91d450f6ad9edb3cbadbd9aa746b176f to your computer and use it in GitHub Desktop.
defmodule MailService.SendAdapters.SendGrid do
@mailer_url "https://api.sendgrid.com/v3/mail/send"
@doc """
Send a mail to a list of persons (recipients)
* from from address
* recipients array of email addresses
* subject subject text
* body text of the email
"""
def send(from, to, subject, body_text, body_html) do
if System.get_env("SEND_GRID_API_KEY") do
HTTPotion.post(@mailer_url, [body: mail_json(from, to, subject, body_text, body_html), headers: headers()])
|> case do
%{status_code: code} when code in (200..299) ->
:ok
error ->
IO.puts "Failed to send mail: #{inspect error}"
{:error, error}
end
else
:ok
end
end
defp mail_json(from, to, subject, body_text, body_html) do
%{
"personalizations"=> [
%{
"to"=> [
%{"email"=> to }
]
}
],
"from"=> %{
"email"=> from
},
"subject"=> subject,
"content"=> [
%{
"type"=> "text/plain",
"value"=> body_text
},
%{
"type"=> "text/html",
"value"=> body_html
}
]
}
|> Poison.encode!
end
defp headers do
[
"Content-Type": "application/json",
"Authorization": "Bearer #{System.get_env("SEND_GRID_API_KEY")}"
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment