How to Send Email in Elixir: Swoosh, Phoenix and API
Pranav Patel
Co-founderยท13 min read
On this page

Send email from Elixir with Swoosh over SMTP or with an email API. Copy-paste examples for Phoenix, HTML email, attachments, background sending with Oban and retries without duplicates.
Elixir apps send email with Swoosh, the mailer library that every new Phoenix app already includes. For production, point Swoosh at a provider over SMTP with the gen_smtp adapter, or skip SMTP and call an email API over HTTPS.
This guide covers Swoosh over SMTP, the Reloop Elixir SDK, Phoenix, then the production details: attachments, background sending with Oban and safe retries.
Working in another language? See how to send email in Python or Node.js.
Which approach should you use?
{:swoosh, ...} and {:gen_smtp, ...}{:reloop, "~> 0.1.3"}Swoosh.Email pipelinehtml, text, attachments{:error, {type, reason}} from gen_smtp{:error, message} with the status and bodyphx.gen.auth emailsIf you want Phoenix's generated auth emails and any library that uses your mailer to go through one provider, use SMTP. If you are writing the send call yourself, use the API.
Prerequisites
- Elixir 1.15 or later on Erlang/OTP 25 or later (for
:public_key.cacerts_get/0) - A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep the key in the environment or a secrets manager, never in your code or git.
Method 1: Send email with Swoosh over SMTP
Swoosh builds the message. The SMTP adapter hands it to gen_smtp, which you add yourself:
1defp deps do2 [3 {:swoosh, "~> 1.16"},4 {:gen_smtp, "~> 1.2"}5 ]6endDefine a mailer:
1defmodule Acme.Mailer do2 use Swoosh.Mailer, otp_app: :acme3endConfigure it in config/runtime.exs, so the key is read from the environment when the app boots, not baked in at compile time:
1import Config2
3config :acme, Acme.Mailer,4 adapter: Swoosh.Adapters.SMTP,5 relay: "smtp.reloop.sh",6 port: 587,7 username: "reloop",8 password: System.get_env("RELOOP_API_KEY"),9 ssl: false,10 tls: :always,11 auth: :always,12 tls_options: [13 versions: [:"tlsv1.2", :"tlsv1.3"],14 verify: :verify_peer,15 cacerts: :public_key.cacerts_get(),16 server_name_indication: ~c"smtp.reloop.sh",17 depth: 99,18 customize_hostname_check: [19 match_fun: :public_key.pkix_verify_hostname_match_fun(:https)20 ]21 ]The username can be any string. The password is your API key. tls: :always upgrades the connection with STARTTLS and refuses to send if the upgrade fails.
Do not skip tls_options. Without them, gen_smtp offers only TLS 1.0 to 1.2 and does not load trusted certificates, and on recent OTP versions the handshake fails with :tls_failed.
Outside Phoenix, Swoosh also expects an HTTP client for its API adapters. The SMTP adapter does not need one, so turn it off:
config :swoosh, :api_client, falseNow build and send an email:
1import Swoosh.Email2
3email =4 new()5 |> from({"Acme", "hello@mail.acme.com"})6 |> to("user@example.com")7 |> subject("Welcome to Acme")8 |> text_body("Welcome! Thanks for signing up.")9 |> html_body("<h1>Welcome!</h1><p>Thanks for signing up.</p>")10
11{:ok, _receipt} = Acme.Mailer.deliver(email)Always set both bodies. Swoosh sends them as a multipart message, and the plain-text part helps with spam filters and text-only clients.
When port 587 is blocked
Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port number changes:
1config :acme, Acme.Mailer,2 adapter: Swoosh.Adapters.SMTP,3 relay: "smtp.reloop.sh",4 port: 25875 # ...plus the same username, password, tls and tls_options as aboveReloop does not offer implicit TLS on port 465, so keep ssl: false. Setting ssl: true makes gen_smtp expect TLS from the first byte, which is what port 465 does. If the connection hangs or times out, see SMTP ports explained.
Handle SMTP errors
deliver/1 never raises for a failed send. It returns a tuple, and the reason comes from gen_smtp:
1require Logger2
3case Acme.Mailer.deliver(email) do4 {:ok, _receipt} ->5 :ok6
7 {:error, {_type, {:permanent_failure, _host, :auth_failed}}} ->8 Logger.error("SMTP login failed: check RELOOP_API_KEY")9
10 {:error, {_type, {_failure, _host, :tls_failed}}} ->11 Logger.error("STARTTLS failed: check tls_options")12
13 {:error, reason} ->14 Logger.error("Send failed: #{inspect(reason)}")15endUse deliver!/1 instead if you want an exception on failure.
Can I send with Gmail from Elixir?
For a personal script, yes: use smtp.gmail.com on port 587 with an App Password and the same Swoosh settings. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.
Method 2: Send email with the Elixir SDK
Install
1defp deps do2 [3 {:reloop, "~> 0.1.3"},4 {:req, "~> 0.5", override: true}5 ]6endThen run mix deps.get.
The SDK uses Req for HTTP, and version 0.1.3 declares req ~> 0.3.0. New Phoenix apps already depend on {:req, "~> 0.5"}, so Mix cannot resolve both until you mark your Req line with override: true. The SDK's send call works on current Req releases.
Send an email
1client = Reloop.client(System.fetch_env!("RELOOP_API_KEY"))2
3case Reloop.Services.Mail.send(client, %{4 from: "Acme <hello@mail.acme.com>",5 to: "user@example.com",6 subject: "Welcome to Acme",7 html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",8 text: "Welcome! Thanks for signing up."9 }) do10 {:ok, result} -> IO.puts("Sent: #{result["id"]}")11 {:error, message} -> IO.puts("Failed: #{message}")12endThe SDK returns errors instead of raising them. On success you get {:ok, map} with the decoded response, using string keys such as "id" and "messageId". On failure you get {:error, message}, where message is a string like "Reloop API Error: 401 ..." for an API error or "Reloop Network Error: ..." when the request never got a response.
The client is a plain struct holding your key and the base URL, so building it is cheap and there is no process to start or stop. Reloop.client/1 raises ArgumentError if the key is nil or empty, which catches a missing environment variable early.
Send to several recipients
1Reloop.Services.Mail.send(client, %{2 from: "Acme <hello@mail.acme.com>",3 to: ["ada@example.com", "grace@example.com"],4 cc: "team@acme.com",5 reply_to: "support@acme.com",6 subject: "Your weekly report",7 text: "Here is your report.",8 tags: [%{name: "type", value: "weekly_report"}]9})Every address in to sees the others. For personalized mail, send one message per recipient.
Send a stored template
Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:
1Reloop.Services.Mail.send(client, %{2 from: "Acme <hello@mail.acme.com>",3 to: "user@example.com",4 subject: "Welcome to Acme",5 template: %{6 id: "tmpl_welcome",7 variables: %{first_name: "Ada", plan: "Pro"}8 }9})See templates for variables and defaults.
Phoenix
Swoosh over SMTP
mix phx.new generates Acme.Mailer, uses Swoosh.Adapters.Local in development and Swoosh.Adapters.Test in tests. Production is left for you to configure, which is where Reloop goes.
Add {:gen_smtp, "~> 1.2"} to your deps, then put the SMTP settings inside the prod block of config/runtime.exs, next to the commented-out mailer example the generator left there:
1if config_env() == :prod do2 # ...database and endpoint config...3
4 config :acme, Acme.Mailer,5 adapter: Swoosh.Adapters.SMTP,6 relay: "smtp.reloop.sh",7 port: 587,8 username: "reloop",9 password: System.fetch_env!("RELOOP_API_KEY"),10 ssl: false,11 tls: :always,12 auth: :always,13 tls_options: [14 versions: [:"tlsv1.2", :"tlsv1.3"],15 verify: :verify_peer,16 cacerts: :public_key.cacerts_get(),17 server_name_indication: ~c"smtp.reloop.sh",18 depth: 99,19 customize_hostname_check: [20 match_fun: :public_key.pkix_verify_hostname_match_fun(:https)21 ]22 ]23endSystem.fetch_env!/1 makes the release refuse to boot without a key, instead of failing on the first send. The generated config/prod.exs sets config :swoosh, api_client: Swoosh.ApiClient.Req. You can leave it: the SMTP adapter does not use it.
That is all phx.gen.auth needs. Its UserNotifier builds emails with Swoosh and calls Mailer.deliver/1, so login links, confirmations and password reset emails all go through Reloop. Change its from to an address on your verified domain:
|> from({"Acme", "hello@mail.acme.com"})Call the SDK from a context
For emails you write yourself, keep the API calls in a context module, so controllers and LiveViews never touch the client directly. Read the key in config/runtime.exs:
config :acme, :reloop_api_key, System.get_env("RELOOP_API_KEY")1defmodule Acme.Emails do2 defp client do3 Reloop.client(Application.fetch_env!(:acme, :reloop_api_key))4 end5
6 def send_contact_message(email, message) do7 Reloop.Services.Mail.send(client(), %{8 from: "Acme Website <contact@mail.acme.com>",9 to: "support@acme.com",10 reply_to: email,11 subject: "New message from #{email}",12 text: message13 })14 end15end1defmodule AcmeWeb.ContactController do2 use AcmeWeb, :controller3 require Logger4
5 def create(conn, %{"email" => email, "message" => message}) do6 case Acme.Emails.send_contact_message(email, message) do7 {:ok, %{"id" => id}} ->8 json(conn, %{id: id})9
10 {:error, reason} ->11 Logger.error("Contact email failed: #{reason}")12
13 conn14 |> put_status(:bad_gateway)15 |> json(%{error: "Could not send message"})16 end17 end18endThe visitor's address goes in reply_to, never in from. You can only send from your verified domain, and putting someone else's domain in from fails DMARC.
Sending inside the request is fine for a contact form, where the visitor wants to know it worked. For signup and order emails, send from a job instead (see below).
Attachments
With the SDK, pass base64 content:
1pdf = File.read!("invoice-1042.pdf")2
3Reloop.Services.Mail.send(client, %{4 from: "Acme Billing <billing@mail.acme.com>",5 to: "user@example.com",6 subject: "Your invoice #1042",7 text: "Your invoice is attached.",8 attachments: [9 %{10 filename: "invoice-1042.pdf",11 content: Base.encode64(pdf),12 content_type: "application/pdf"13 }14 ]15})With Swoosh, pass a file path to attachment/2, or build the attachment from data you already have in memory:
1email2|> attachment("invoice-1042.pdf")3
4email5|> attachment(6 Swoosh.Attachment.new({:data, pdf},7 filename: "invoice-1042.pdf",8 content_type: "application/pdf"9 )10)Keep attachments small. Many inboxes reject messages over 25 MB, and large files hurt deliverability. For big files, send a signed download link.
Send in the background with Oban
Sending inside a web request adds latency and fails the request when the provider is slow. Oban stores jobs in your database, so they survive restarts and deploys, and it retries failed jobs with exponential backoff.
After following Oban's installation guide, add a queue for email:
1config :acme, Oban,2 repo: Acme.Repo,3 queues: [mailers: 10]To decide whether to retry, the worker needs the HTTP status. The SDK puts the status inside its error string, so the worker calls the API with Req directly, which also lets it send the idempotency key from the next section:
1defmodule Acme.Workers.WelcomeEmail do2 use Oban.Worker, queue: :mailers, max_attempts: 53
4 @impl Oban.Worker5 def perform(%Oban.Job{args: %{"user_id" => user_id, "email" => email}}) do6 response =7 Req.post("https://reloop.sh/api/mail/v1/send",8 headers: [9 {"x-api-key", Application.fetch_env!(:acme, :reloop_api_key)},10 {"idempotency-key", "welcome-#{user_id}"}11 ],12 json: %{13 from: "Acme <hello@mail.acme.com>",14 to: email,15 subject: "Welcome to Acme",16 text: "Thanks for signing up."17 },18 receive_timeout: 30_000,19 retry: false20 )21
22 case response do23 {:ok, %Req.Response{status: status, body: body}} when status in 200..299 ->24 {:ok, body["id"]}25
26 {:ok, %Req.Response{status: status, body: body}}27 when status in [409, 429] or status >= 500 ->28 {:error, "Reloop returned #{status}: #{inspect(body)}"}29
30 {:ok, %Req.Response{status: status, body: body}} ->31 {:cancel, "Reloop returned #{status}: #{inspect(body)}"}32
33 {:error, exception} ->34 {:error, exception}35 end36 end37endRetry network errors, 429 and 5xx by returning {:error, reason}: Oban schedules another attempt. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time, so return {:cancel, reason} and Oban stops. 409 is the one exception, covered below. retry: false turns off Req's own retries, so Oban is the only thing retrying.
Enqueue the job in the same transaction that creates the user, so you never send a welcome email for a signup that rolled back:
1Ecto.Multi.new()2|> Ecto.Multi.insert(:user, User.registration_changeset(%User{}, attrs))3|> Oban.insert(:welcome_email, fn %{user: user} ->4 Acme.Workers.WelcomeEmail.new(%{user_id: user.id, email: user.email})5end)6|> Repo.transaction()Retries without duplicate emails
A request times out and Oban retries the job. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.
The Elixir SDK does not accept extra headers, so set it with Req as in the worker above:
1headers: [2 {"x-api-key", Application.fetch_env!(:acme, :reloop_api_key)},3 {"idempotency-key", "welcome-#{user_id}"}4]Base the key on the business event (welcome-#{user_id}, receipt-#{order_id}), not a new UUID per attempt, so every attempt of the job sends the same key. A 409 means a request with that key is still running, so retrying it later returns the original result. Reusing a key with a different body returns 422, which the worker cancels.
Testing without sending real email
- Phoenix tests: the generated
config/test.exsalready usesSwoosh.Adapters.Test.import Swoosh.TestAssertionsand callassert_email_sent(subject: "Welcome to Acme"). - Oban jobs: run Oban with
testing: :manualin tests and check enqueued jobs withassert_enqueuedfromOban.Testing, instead of calling the API. - Local preview: in development, Phoenix uses
Swoosh.Adapters.Local. Openhttp://localhost:4000/dev/mailboxto see every email your app sent. - Local SMTP: run Mailpit with
docker run -p 1025:1025 -p 8025:8025 axllent/mailpitand point the SMTP adapter at it withrelay: "localhost", port: 1025, ssl: false, tls: :never, auth: :never. Openhttp://localhost:8025to see the messages. - Staging: send to test addresses so you do not hurt your sender reputation with bounces.
Production checklist
- API key in an environment variable, read in
config/runtime.exs - Sending domain verified with SPF, DKIM and DMARC
-
fromon your verified domain; user addresses inreply_to - Both HTML and plain-text bodies
-
tls: :alwayswithtls_optionsthat verify the certificate - Sending in an Oban job, not the request
- Retries only on network errors,
429and5xx;{:cancel, reason}for other4xx - Idempotency keys on anything that retries
- Webhooks for bounces and complaints
- Disposable addresses blocked at signup (how)
FAQ
With Swoosh, set an HTML body and a plain-text body on the email, then call deliver on your mailer. Swoosh sends both as one multipart message. With the Reloop SDK, pass html and text keys in the map you give to Reloop.Services.Mail.send.
ssl: true starts TLS immediately, which is what port 465 expects. tls: :always connects in plain text and upgrades with STARTTLS, which is what port 587 expects. Reloop uses STARTTLS on every port, so set ssl: false and tls: :always.
gen_smtp's default TLS options offer TLS 1.0 to 1.2 and load no trusted certificates, which recent OTP versions reject. Pass tls_options that turn on peer verification, load the system CA certificates and set the server name to the SMTP host, as shown in the config above.
Version 0.1.3 of the SDK declares req ~> 0.3.0, and new Phoenix apps depend on req ~> 0.5. Add override: true to your own Req dependency and Mix resolves the newer version for both.
Yes. Pass your instance's URL as the base_url option when you build the client, as the second argument to Reloop.client. The default is https://reloop.sh.
Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


