Resend Template Email
A simple package for sending emails using a template fetched from your backend API and sending it via the Resend API. This package allows dynamic variable substitution in your email templates.
Installation
To install this package, run:
npm install resend-template
Usage
Prerequisites
Before using this package, ensure that:
- You have a Resend account and API key. You can get it by signing up at Resend.
Import the sendTemplateEmail
function
import { sendTemplateEmail } from 'resend-template';
Example Usage
You can send an email using a template as follows:
const apiKey = 'your_resend_api_key';
const from = 'your-email@example.com';
const to = 'recipient@example.com';
const templateId = 'your-template-id';
const variables = {
name: 'John Doe',
subject: 'Welcome to Our Service',
};
sendTemplateEmail({ apiKey, from, to, templateId, variables })
.then(response => {
console.log('Email sent successfully:', response);
})
.catch(err => {
console.error('Error sending email:', err);
});
Template Structure
Your backend should have an endpoint that serves the template. The template should include HTML and placeholders in the format {{variableName}}
. Here's an example:
{
"templateId": "welcome-email",
"subject": "Welcome, {{name}}!",
"html": "<h1>Hello {{name}},</h1><p>Welcome to our service! We are happy to have you onboard.</p>"
}
When you call the sendTemplateEmail
function, the placeholders in the template will be replaced with the values provided in the variables
object.
Example Response
When the email is successfully sent, you'll get a response like this:
{
"id": "email-id",
"status": "queued",
"from": "your-email@example.com",
"to": "recipient@example.com",
"subject": "Welcome, John Doe!",
"html": "<h1>Hello John Doe,</h1><p>Welcome to our service! We are happy to have you onboard.</p>"
}
Configuration
The following parameters are required to use the sendTemplateEmail
function:
apiKey
(string): Your Resend API key.
from
(string): The sender's email address.
to
(string): The recipient's email address.
templateId
(string): The ID of the template you want to use.
variables
(object): An object containing variables to replace in the template. The keys should match the placeholders in the template.
Example variables
object:
const variables = {
name: 'John Doe',
subject: 'Welcome to Our Service'
};
import { sendTemplateEmail } from './index.js';
import dotenv from 'dotenv';
dotenv.config();
const testSendEmail = async () => {
const response = await sendTemplateEmail({
apiKey: process.env.RESEND_API_KEY,
from: 'example@gmail.com',
to: 'your-email@gmail.com',
templateId: 'password-reset',
variables: {
subject: 'Password Reset Link : www.digivjay.kadam.com',
name: "John Doe",
reset_link: "https://yourwebsite.com/reset-password?token=xyz",
year: "2025"
}
});
console.log('Email Response:', response);
};
testSendEmail();
License
This project is licensed under the MIT License - see the LICENSE file for details.