Send Emails With Resend
In this tutorial, you will learn how to send transactional emails from Workers using Resend ↗. At the end of this tutorial, you’ll be able to:
- Create a Worker to send emails.
- Sign up and add a Cloudflare domain to Resend.
- Send emails from your Worker using Resend.
- Store API keys securely with secrets.
To continue with this tutorial, you’ll need:
- A Cloudflare account ↗, if you don’t already have one.
- A registered domain.
- Installed npm ↗.
- A Resend account ↗.
Start by using C3 to create a Worker project in the command line, then, answer the prompts:
Alternatively, you can use CLI arguments to speed things up:
This creates a simple hello-world Worker having the following content:
If you don’t already have a Resend account, you can sign up for a free account here ↗. After signing up, go to Domains
using the side menu, and click the button to add a new domain. On the modal, enter the domain you want to add and then select a region.
Next, you’re presented with a list of DNS records to add to your Cloudflare domain. On your Cloudflare dashboard, select the domain you entered earlier and navigate to DNS
> Records
. Copy/paste the DNS records (DKIM, SPF, and DMARC records) from Resend to your Cloudflare domain.
When that’s done, head back to Resend and click on the Verify DNS Records
button. If all records are properly configured, your domain status should be updated to Verified
.
Lastly, navigate to API Keys
with the side menu, to create an API key. Give your key a descriptive name and the appropriate permissions. Click the button to add your key and then copy your API key to a safe location.
The final step is putting it all together in a Worker. Open up a terminal in the directory of the Worker you created earlier. Then, install the Resend SDK:
In your Worker, import and use the Resend library like so:
To test your code locally, run the following command and navigate to http://localhost:8787/ ↗ in a browser:
Deploy your Worker with npm run deploy
.
Sensitive information such as API keys and token should always be stored in secrets. All secrets are encrypted to add an extra layer of protection. That said, it’s a good idea to move your API key to a secret and access it from the environment of your Worker.
To add secrets for local development, create a .dev.vars
file which works exactly like a .env
file:
Also ensure the secret is added to your deployed worker by running:
The added secret can be accessed on via the env
parameter passed to your Worker’s fetch event handler:
And finally, deploy this update with npm run deploy
.