Overview
The Email API provides functionality for sending individual and mass emails through an SMTP-based queue system with rate limiting.
Email Operations
send
Send an email to a single contact.
db.emails.send(
contactId: string,
subject: string,
content: string
): Promise<EmailLog | null>
ID of the contact to send to
Log entry for the queued email, or null if contact not found
Example:
const log = await db.emails.send(
'c_12345',
'Welcome to CAFH',
'<p>Hola! Welcome to our community...</p>'
);
if (log) {
console.log('Email queued:', log.id);
}
sendMass
Send the same email to multiple recipients.
db.emails.sendMass(
recipients: string[],
subject: string,
content: string
): Promise<{ success: boolean }>
Object with success status
Example:
const subscribedContacts = db.crm.getAll()
.filter(c => c.status === 'Subscribed')
.map(c => c.email);
const result = await db.emails.sendMass(
subscribedContacts,
'Monthly Newsletter',
'<h1>March Newsletter</h1><p>...content...</p>'
);
console.log('Mass email result:', result.success);
Email Logs
getLogs
Retrieve email delivery logs.
db.emails.getLogs(contactId?: string): EmailLog[]
Filter logs for a specific contact
Example:
// All logs
const allLogs = db.emails.getLogs();
// Logs for specific contact
const contactLogs = db.emails.getLogs('c_12345');
getMetrics
Get email performance metrics.
db.emails.getMetrics(): EmailMetrics
Aggregated email statistics
Example:
const metrics = db.emails.getMetrics();
console.log('Total sent:', metrics.totalSent);
console.log('Open rate:', metrics.openRate);
console.log('Click rate:', metrics.clickRate);
SMTP Configuration
getSMTPConfig
Retrieve current SMTP settings.
db.emails.getSMTPConfig(): SMTPConfig
SMTP configuration object
Example:
const config = db.emails.getSMTPConfig();
console.log('SMTP Host:', config.host);
console.log('From:', config.fromEmail);
updateSMTPConfig
Update SMTP configuration.
db.emails.updateSMTPConfig(config: SMTPConfig): SMTPConfig
Complete SMTP configuration
The updated configuration
Example:
db.emails.updateSMTPConfig({
host: 'mail.cafh.cl',
port: '465',
secure: true,
user: '[email protected]',
pass: 'your-password',
fromEmail: '[email protected]',
fromName: 'Cafh'
});
Queue Management
getQueueStatus
Check the email queue and rate limiting status.
db.emails.getQueueStatus(): Promise<{
pending: number;
sent: number;
failed: number;
sentCountThisHour: number;
limit: number;
}>
Queue statistics and rate limit info
Example:
const status = await db.emails.getQueueStatus();
console.log(`Queue: ${status.pending} pending`);
console.log(`Rate limit: ${status.sentCountThisHour}/${status.limit} this hour`);
Backend Queue API
The backend server provides REST endpoints for the email queue system.
POST /api/email/queue
Add emails to the processing queue.
fetch('/api/email/queue', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recipients: ['[email protected]'],
subject: 'Hello',
content: '<p>Content</p>'
})
});
Request Body:
Array of recipient email addresses
Response:
{
"message": "3 emails added to queue",
"queueSize": 15
}
GET /api/email/status
Get queue status and statistics.
fetch('/api/email/status')
.then(res => res.json())
.then(data => console.log(data));
Response:
{
"pending": 12,
"sent": 450,
"failed": 3,
"sentCountThisHour": 65,
"limit": 80
}
Types
EmailLog
interface EmailLog {
id: string;
contactId: string;
subject: string;
sentAt: string;
status: 'Delivered' | 'Opened' | 'Clicked' | 'Bounced' | 'Failed' | 'Queued';
openedAt?: string;
clickedAt?: string;
errorMessage?: string;
campaignName?: string;
}
EmailMetrics
interface EmailMetrics {
totalSent: number;
openRate: number;
clickRate: number;
bounceRate: number;
history: {
date: string;
sent: number;
opened: number;
clicked: number
}[];
}
SMTPConfig
interface SMTPConfig {
host: string;
port: string;
secure: boolean;
user: string;
pass: string;
fromEmail: string;
fromName: string;
}
Rate Limiting
The queue system respects SMTP provider rate limits:
- Default limit: 80 emails per hour
- Configurable via
MAX_EMAILS_PER_HOUR env variable
- Queue automatically processes pending emails
- Hourly counter resets every 60 minutes
Emails are queued locally and processed by the backend worker every 30 seconds.