Skip to content

Instantly share code, notes, and snippets.

@blackfist
Last active April 3, 2018 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blackfist/bcc3b0866787e48437fc to your computer and use it in GitHub Desktop.
Save blackfist/bcc3b0866787e48437fc to your computer and use it in GitHub Desktop.
Example of using Elixir and HTTPotion to send mail to Mailgun using the api.
defmodule Mailgun do
@doc """
Sends a basic message to an address. Expects a mailgun domain environment
variable (MAILGUN_DOMIAN) and a mailgun api key environment variable
(MAILGUN_API_KEY).
"""
@spec mail(String.t) :: String.t
def mail(toAddress) do
url = "https://api.mailgun.net/v3/#{System.get_env("MAILGUN_DOMAIN")}/messages"
headers = ["User-Agent": "Elixir",
"Content-Type": "application/x-www-form-urlencoded"]
params = ["from=noreply@heroku.com",
"to=#{toAddress}",
"subject=Missing GitHub 2FA",
"text=Can you believe that?"]
user = {"api", System.get_env("MAILGUN_API_KEY")}
response = HTTPotion.post url, [body: Enum.join(params, "&"),
basic_auth: user,
headers: headers]
case response.status_code do
200 -> "Message queued for delivery to #{toAddress}"
400 -> "Some kind of message error. Mailgun returned #{Poison.decode!(response.body) |> Map.get("message")}"
401 -> "Some kind of authentication error. Mailgun returned #{response.body}"
_ -> "Something wrong with the request"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment