Resend + Elixir
Mix.install([
{:resend, "~> 0.4.0"},
{:kino, "~> 0.9.4"}
])
Create a client
To start using Resend, create a client
with the API key you created in your web dashboard:
client = Resend.client(api_key: System.fetch_env!("LB_RESEND_KEY"))
Note that if you choose to configure Resend in your app config, passing a client struct is always optional.
Sending email
We’ve created some inputs to make sending emails easy. Feel free to replace these as needed!
to = Kino.Input.text("To") |> Kino.render()
from = Kino.Input.text("From", default: "onboarding@resend.dev") |> Kino.render()
subject = Kino.Input.text("Subject", default: "Hello World") |> Kino.render()
text = Kino.Input.textarea("Text", default: "It works!") |> Kino.render()
Kino.nothing()
Read the input values and send our first email with Resend:
{:ok, email} =
Resend.Emails.send(
client,
%{
to: Kino.Input.read(to),
from: Kino.Input.read(from),
subject: Kino.Input.read(subject),
text: Kino.Input.read(text)
}
)
We can get details about this email by looking it up with its ID:
Resend.Emails.get(client, email.id)
Managing domains
Lets create a new domain, we’ll just use a random string:
{:ok, domain} =
Resend.Domains.create(
client,
name: Base.encode16(:rand.bytes(8), case: :lower) <> ".com"
)
We can list all our domains, to see that our new one has been added:
Resend.Domains.list(client)
Now that we’ve demonstrated that we can create domains, lets remove the random one we created:
{:ok, _deleted} = Resend.Domains.remove(client, domain.id)
Managing API keys
We can manage API keys too. Let’s create a new one that can only send to our new domain. Note that we must also apply the "sending_access"
permission when specifying a :domain_id
.
{:ok, api_key} =
Resend.ApiKeys.create(client,
name: "For random domain",
permission: "sending_access",
domain_id: domain.id
)
The :token
field we get back contains our new API token. It’s the only time it’s show, so make sure to save it some place where it won’t get lost.
Let’s take a look at our new API key in the list of all API keys:
Resend.ApiKeys.list(client)
Nice!
Lastly, we’ll remove the API key we created to keep our account nice and tidy:
{:ok, _deleted} = Resend.ApiKeys.remove(client, api_key.id)