- Published on
Sending email with Attachments using Resend API in Node.js
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Resend is a developer-friendly email provider using which you can send transactional emails easily.
In this post, let's see how to add file attachments to the email.
The only dependency we've is getting the API key which you can easily get from Resend dashboard
As per the docs, we can send attachments in two ways.
- Directly giving hosted file's URL
- Passing the content of the file as a buffer/string
Passing the attachment file as a URL
It's straight forward, pass the path to the hosted file as an URL (make sure it's public) in attachments[].path
{
"from": "onboarding@resend.dev",
"to": "example@gmail.com",
"subject": "An email with file Attachment",
"text": "It works!",
"attachments":[
{
"filename":"example.jpg",
"path":"https://nesin.io/_next/image?url=%2Fstatic%2Fimages%2FAshikNesin.jpg&w=384&q=75"
}
]
}
It'll take care of the rest
Passing the content of the file as a Buffer
First, we'll be reading the file as a buffer and then pass it to the API call
npm install node-fetch
import fetch from "node-fetch";
const RESEND_AUTH_KEY = process.env.RESEND_AUTH_KEY
const fileBuffer = await fs.readFile('example.png');
const payload = {
"from": "onboarding@resend.dev",
"to": "example@gmail.com",
"subject": "A email with file Attachment",
"text": "It works!",
"attachments": [
{
filename: "example.png",
content: fileBuffer
}
]
}
const requestOptions = {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${RESEND_AUTH_KEY}`
},
body: JSON.stringify(payload)
};
fetch("https://api.resend.com/emails", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Happy sending emails!