@venturialstd/email
v0.0.2
Published
Email Module with Multiple Transporter Support for Venturial
Keywords
Readme
@venturialstd/email
Email Module with Multiple Transporter Support for Venturial Standard Backend.
Features
- 📧 Multiple transporter support (SMTP, and extensible for others)
- 🔧 Configuration via code or settings service
- 🎨 Handlebars template support - Beautiful, dynamic email templates
- 📊 Database template management - Store and manage templates in database
- 📝 HTML and plain text emails
- 🔄 Attachment support
- 📊 Email logging and tracking - All sent emails are logged with status
- 🚀 Built on top of @nestjs-modules/mailer
Quick Links
- Database Template Management - Store templates in database
- Handlebars Templates Guide - Complete guide to using templates
- Email Logging Documentation - Email tracking and monitoring
- Usage Examples - Comprehensive usage examples
Installation
npm install @venturialstd/emailUsage
Import the Module
import { EmailModule } from '@venturialstd/email';
@Module({
imports: [
EmailModule,
// ... other modules
],
})
export class AppModule {}Send Emails
import { EmailService, EmailConfig } from '@venturialstd/email';
@Injectable()
export class MyService {
constructor(private readonly emailService: EmailService) {}
async sendWelcomeEmail() {
const config: EmailConfig = {
transporter: 'SMTP',
smtp: {
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'password',
},
},
};
await this.emailService.sendEmail(config, {
to: '[email protected]',
subject: 'Welcome!',
html: '<h1>Welcome to our platform!</h1>',
});
}
}Send Emails with Handlebars Templates
The module includes pre-built Handlebars templates and helper methods:
// Welcome email
await emailService.sendWelcomeEmail(null, {
to: '[email protected]',
name: 'John Doe',
message: 'Thank you for joining our platform!',
actionUrl: 'https://app.example.com/onboarding',
});
// Password reset email
await emailService.sendPasswordResetEmail(null, {
to: '[email protected]',
name: 'John Doe',
resetUrl: 'https://app.example.com/reset?token=abc123',
expirationTime: 30,
});
// Notification email
await emailService.sendNotificationEmail(null, {
to: '[email protected]',
name: 'John Doe',
title: 'Order Confirmation',
notificationTitle: 'Your order has been confirmed!',
message: 'Order #12345 is being processed.',
});
// Custom template
await emailService.sendEmailWithTemplate(null, {
to: '[email protected]',
subject: 'Custom Email',
template: 'my-custom-template',
context: {
customVariable: 'value',
},
});See HANDLEBARS_TEMPLATES.md for complete template documentation.
Configuration Options
SMTP Configuration
const config: EmailConfig = {
transporter: 'SMTP',
smtp: {
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '[email protected]',
pass: 'your-password',
},
},
defaults: {
from: '"Your Name" <[email protected]>',
},
};Using Settings Service
If no config is provided, the module will attempt to load configuration from the Settings Service:
EMAIL_TRANSPORTER- Transport type (default: 'SMTP')EMAIL_SMTP_HOST- SMTP server hostEMAIL_SMTP_PORT- SMTP server portEMAIL_SMTP_SECURE- Use SSL/TLS (true/false)EMAIL_SMTP_USER- SMTP authentication userEMAIL_SMTP_PASSWORD- SMTP authentication passwordEMAIL_DEFAULT_FROM- Default sender email address
API
EmailService
sendEmail(config, options)
Sends an email with the specified options. All emails are automatically logged to the database.
Parameters:
config: EmailConfig | null- Email configuration (transporter settings)options: SendEmailOptions- Email options (to, subject, html, etc.)
Returns: Promise<void>
getEmailLogs(options?)
Retrieves email logs with optional filtering.
Parameters:
options?: Optional filtering optionsstatus?: EmailStatus- Filter by status (PENDING, SENT, FAILED)to?: string- Filter by recipient emailfrom?: string- Filter by sender emailstartDate?: Date- Filter from this dateendDate?: Date- Filter until this datelimit?: number- Limit number of results
Returns: Promise<EmailLog[]>
Example:
// Get all failed emails
const failedEmails = await emailService.getEmailLogs({
status: EmailStatus.FAILED,
limit: 10,
});
// Get emails sent to specific recipient
const userEmails = await emailService.getEmailLogs({
to: '[email protected]',
});getEmailLogById(id)
Gets a single email log by ID.
Parameters:
id: string- Email log ID
Returns: Promise<EmailLog | null>
getEmailLogStats(startDate?, endDate?)
Gets email statistics for a date range.
Parameters:
startDate?: Date- Start date for statisticsendDate?: Date- End date for statistics
Returns: Promise<{ total: number; sent: number; failed: number; pending: number }>
Example:
const stats = await emailService.getEmailLogStats(
new Date('2024-01-01'),
new Date('2024-01-31')
);
console.log(`Total emails: ${stats.total}, Sent: ${stats.sent}, Failed: ${stats.failed}`);Email Logging
All emails sent through the service are automatically logged to the email_log table with the following information:
- Recipient(s): to, cc, bcc
- Sender: from address
- Content: subject, text, html
- Status: PENDING, SENT, or FAILED
- Metadata: Additional information like template name, config source
- Timestamps: Created, updated, and sent timestamps
- Error tracking: Error messages for failed emails
Email Log Entity
export enum EmailStatus {
PENDING = 'PENDING',
SENT = 'SENT',
FAILED = 'FAILED',
}
export interface EmailLog {
id: string;
to: string;
from?: string;
cc?: string;
bcc?: string;
subject: string;
textContent?: string;
htmlContent?: string;
transporter: string;
status: EmailStatus;
errorMessage?: string;
metadata?: Record<string, any>;
hasAttachments: boolean;
sentAt?: Date;
createdAt: Date;
updatedAt: Date;
}Types
EmailConfig
interface EmailConfig {
transporter: 'SMTP';
smtp?: SMTPConfig;
defaults?: {
from?: string;
};
}SMTPConfig
interface SMTPConfig {
host: string;
port: number;
secure: boolean;
auth: {
user: string;
pass: string;
};
}SendEmailOptions
interface SendEmailOptions {
to: string | string[];
subject: string;
text?: string;
html?: string;
from?: string;
cc?: string | string[];
bcc?: string | string[];
attachments?: Array<{
filename: string;
content?: string | Buffer;
path?: string;
}>;
}License
Proprietary - Venturial Standard
