Skip to content

Instantly share code, notes, and snippets.

@fabiancarlos
Forked from mlankenau/send_grid.ex
Created October 19, 2022 01:41
Show Gist options
  • Save fabiancarlos/879f20450caea0628da299d44d5d8ac0 to your computer and use it in GitHub Desktop.
Save fabiancarlos/879f20450caea0628da299d44d5d8ac0 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