NodeJS
Node.js integration examples for Keplars Mail Service
Send emails using Node.js with both REST API and SMTP approaches.
Looking for a better way to build email templates? Check out React Email for component-based email development with TypeScript support.
Installation
npm install axiosBasic Setup
# .env
KEPLERS_API_KEY=kms_your_api_key.live_...REST API Integration
Basic Client
const axios = require('axios');
class KeplarsMailClient {
constructor(apiKey) {
this.client = axios.create({
baseURL: 'https://api.keplars.com',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
}
async sendEmail(emailData) {
try {
const response = await this.client.post('/api/v1/send-email/async', emailData);
return response.data;
} catch (error) {
throw new Error(`Failed to send email: ${error.response?.data?.message || error.message}`);
}
}
async sendInstantEmail(emailData) {
try {
const response = await this.client.post('/api/v1/send-email/instant', emailData);
return response.data;
} catch (error) {
throw new Error(`Failed to send instant email: ${error.response?.data?.message || error.message}`);
}
}
}
module.exports = KeplarsMailClient;Usage Examples
const KeplarsMailClient = require('./keplers-client');
const client = new KeplarsMailClient(process.env.KEPLERS_API_KEY);
async function sendWelcomeEmail(userEmail, userName) {
try {
const result = await client.sendEmail({
to: [userEmail],
subject: `Welcome ${userName}!`,
body: `<h1>Welcome ${userName}!</h1><p>Thank you for joining our platform.</p>`
});
console.log('Email sent:', result);
return result;
} catch (error) {
console.error('Failed to send email:', error.message);
throw error;
}
}
async function sendVerificationEmail(userEmail, code) {
try {
const result = await client.sendInstantEmail({
to: [userEmail],
subject: 'Verify Your Email',
body: `Your verification code: ${code}`
});
console.log('Verification email sent:', result);
return result;
} catch (error) {
console.error('Failed to send verification email:', error.message);
throw error;
}
}
sendWelcomeEmail('[email protected]', 'John');
sendVerificationEmail('[email protected]', '123456');Using Templates
Send emails with pre-designed templates and dynamic content:
const KeplarsMailClient = require('./keplers-client');
const client = new KeplarsMailClient(process.env.KEPLERS_API_KEY);
async function sendTemplateEmail(userEmail, templateId, params) {
try {
const result = await client.sendEmail({
to: [userEmail],
template_id: templateId,
params: params
});
console.log('Template email sent:', result);
return result;
} catch (error) {
console.error('Failed to send template email:', error.message);
throw error;
}
}
// Send order confirmation with template
await sendTemplateEmail(
'[email protected]',
'019a83de-2fc2-7b5f-bfbc-c951fe1200f7',
{
userName: 'John Doe',
orderNumber: '12345',
orderDate: new Date().toISOString(),
amount: 99.99,
items: ['Product A', 'Product B']
}
);Extended Client with Template Support
class KeplarsMailClient {
constructor(apiKey) {
this.client = axios.create({
baseURL: 'https://api.keplars.com',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
}
async sendEmail(emailData) {
try {
const response = await this.client.post('/api/v1/send-email/async', emailData);
return response.data;
} catch (error) {
throw new Error(`Failed to send email: ${error.response?.data?.message || error.message}`);
}
}
async sendTemplateEmail(to, templateId, params, priority = 'queue') {
const endpoint = `/api/v1/send-email/${priority}`;
try {
const response = await this.client.post(endpoint, {
to: Array.isArray(to) ? to : [to],
template_id: templateId,
params
});
return response.data;
} catch (error) {
throw new Error(`Failed to send template email: ${error.response?.data?.message || error.message}`);
}
}
async getTemplates(workspaceId) {
try {
const response = await this.client.get(`/api/v1/templates/list?workspace_id=${workspaceId}`);
return response.data;
} catch (error) {
throw new Error(`Failed to get templates: ${error.response?.data?.message || error.message}`);
}
}
}
module.exports = KeplarsMailClient;Template Usage Examples
const client = new KeplarsMailClient(process.env.KEPLERS_API_KEY);
// Send welcome email with template
await client.sendTemplateEmail(
'[email protected]',
'welcome-template-id',
{
userName: 'Sarah',
companyName: 'Keplars',
dashboardUrl: 'https://app.keplars.com/dashboard'
},
'instant' // Priority: instant, high, queue, bulk
);
// Send order confirmation
await client.sendTemplateEmail(
'[email protected]',
'order-confirmation-template-id',
{
userName: 'John Doe',
orderNumber: 'ORD-12345',
orderDate: new Date().toLocaleDateString(),
totalAmount: '$149.99',
trackingUrl: 'https://tracking.example.com/ORD-12345'
},
'high'
);
// List available templates
const templates = await client.getTemplates('your-workspace-id');
console.log('Available templates:', templates);Express.js Integration
const express = require('express');
const KeplarsMailClient = require('./keplers-client');
const app = express();
const mailClient = new KeplarsMailClient(process.env.KEPLERS_API_KEY);
app.use(express.json());
app.post('/api/send-email', async (req, res) => {
try {
const { email, name } = req.body;
const result = await mailClient.sendEmail({
to: [email],
subject: `Welcome ${name}!`,
body: `<h1>Welcome ${name}!</h1>`
});
res.json({ success: true, data: result });
} catch (error) {
console.error('Failed to send email:', error);
res.status(500).json({ error: 'Failed to send email' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});SMTP Integration
Installation
npm install nodemailerSMTP Client
const nodemailer = require('nodemailer');
class KeplarsEmailSMTPClient {
constructor(smtpConfig) {
this.transporter = nodemailer.createTransporter({
host: 'smtp.keplars.com',
port: 587,
secure: false,
auth: {
user: smtpConfig.username,
pass: smtpConfig.password
}
});
}
async sendEmail(emailData) {
try {
const isHTML = /<\s*(html|body|div|p|span|table|img|a|h[1-6]|ul|ol|li|strong|em|b|i|br)\b[^>]*>/i.test(emailData.body);
const mailOptions = {
to: emailData.to.join(', '),
subject: emailData.subject,
html: isHTML ? emailData.body : undefined,
text: !isHTML ? emailData.body : undefined
};
const info = await this.transporter.sendMail(mailOptions);
return {
success: true,
data: { id: info.messageId, status: 'sent' }
};
} catch (error) {
throw new Error(`SMTP send failed: ${error.message}`);
}
}
}
module.exports = KeplarsEmailSMTPClient;SMTP Usage
const KeplarsEmailSMTPClient = require('./smtp-client');
const smtpClient = new KeplarsEmailSMTPClient({
username: process.env.KEPLERS_SMTP_USERNAME,
password: process.env.KEPLERS_SMTP_PASSWORD
});
async function sendEmailViaSMTP(userEmail, subject, body) {
try {
const result = await smtpClient.sendEmail({
to: [userEmail],
subject: subject,
body: body
});
console.log('SMTP email sent:', result);
return result;
} catch (error) {
console.error('SMTP send failed:', error.message);
throw error;
}
}
sendEmailViaSMTP('[email protected]', 'Test Email', '<p>Hello World!</p>');Next Steps
- React Email Integration - Build emails with React components
- Email Templates - Create reusable templates
- Schedule Emails - Send emails at specific times
- Webhooks - Track delivery status
Choose REST API for advanced features or SMTP for traditional email client integration.