Loading...
Loading...
Send emails from your Node.js application using the Notify'n API.
Create a simple email sending function that you can reuse throughout your application:
// lib/email-client.js
const NOTIFYN_API_KEY = process.env.NOTIFYN_API_KEY;
const NOTIFYN_API_URL = `${API_URL}/api/v1/emails`;async function sendEmail({ from, to, subject, html, text, replyTo }) {
const response = await fetch(NOTIFYN_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${NOTIFYN_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from,
to,
subject,
html,
text,
replyTo,
}),
}); if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to send email');
} return response.json();
}module.exports = { sendEmail };const { sendEmail } = require('./lib/email-client');async function main() {
try {
const result = await sendEmail({
from: 'hello@yourdomain.com',
to: 'user@example.com',
subject: 'Welcome to our service!',
html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
});
console.log('Email sent:', result.id);
} catch (error) {
console.error('Failed to send email:', error.message);
}
}main();const express = require('express');
const { sendEmail } = require('./lib/email-client');const app = express();
app.use(express.json());app.post('/api/contact', async (req, res) => {
const { name, email, message } = req.body; if (!name || !email || !message) {
return res.status(400).json({ error: 'All fields required' });
} try {
await sendEmail({
from: 'notifications@yourdomain.com',
to: 'you@yourdomain.com',
replyTo: email,
subject: `Contact Form: ${name}`,
html: `
<h2>New message from ${name}</h2>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Message:</strong> ${message}</p>
`,
}); res.json({ success: true });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to send message' });
}
});app.listen(3000);// lib/email-client.ts
interface EmailOptions {
from: string;
to: string | string[];
subject: string;
html?: string;
text?: string;
replyTo?: string;
cc?: string[];
bcc?: string[];
headers?: Record<string, string>;
tags?: Array<{ name: string; value: string }>;
}interface EmailResponse {
success: boolean;
id: string;
message: string;
}const NOTIFYN_API_KEY = process.env.NOTIFYN_API_KEY!;
const NOTIFYN_API_URL = `${API_URL}/api/v1/emails`;export async function sendEmail(options: EmailOptions): Promise<EmailResponse> {
const response = await fetch(NOTIFYN_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${NOTIFYN_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(options),
}); if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to send email');
} return response.json();
}async function sendEmailWithRetry(options, maxRetries = 3) {
let lastError;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(NOTIFYN_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${NOTIFYN_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(options),
}); // Handle rate limiting
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || 60;
await sleep(parseInt(retryAfter) * 1000);
continue;
} if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
} return response.json();
} catch (error) {
lastError = error;
// Exponential backoff
await sleep(Math.pow(2, attempt) * 1000);
}
} throw lastError;
}function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}