Email Integration Documentation
This document describes the email system integration in DeployStack, including the email service, template system, and usage examples.
Overview
The email system provides a comprehensive solution for sending templated emails using:
- Nodemailer: For SMTP email delivery
- Pug Templates: For beautiful, maintainable email templates
- Global Settings Integration: Automatic SMTP configuration from global settings
- Zod Validation: Type-safe email parameter validation
- Template Caching: Performance optimization for template rendering
Architecture
src/email/
├── emailService.ts # Main email service with SMTP integration
├── templateRenderer.ts # Pug template compilation and rendering
├── types.ts # TypeScript interfaces and Zod schemas
├── index.ts # Module exports
└── templates/
├── layouts/
│ ├── base.pug # Main email layout
│ ├── header.pug # Email header component
│ └── footer.pug # Email footer component
├── welcome.pug # Welcome email template
├── password-reset.pug # Password reset template
└── notification.pug # General notification template
SMTP Configuration
The email system automatically integrates with your existing SMTP global settings. Ensure the following settings are configured in the global settings:
Setting | Required | Description |
---|---|---|
smtp.host | ✅ | SMTP server hostname (e.g., smtp.gmail.com) |
smtp.port | ✅ | SMTP server port (587 for TLS, 465 for SSL) |
smtp.username | ✅ | SMTP authentication username |
smtp.password | ✅ | SMTP authentication password (encrypted) |
smtp.secure | ❌ | Use SSL/TLS connection (default: true) |
smtp.from_name | ❌ | Default sender name (default: DeployStack) |
smtp.from_email | ❌ | Default sender email (default: username) |
Basic Usage
import { EmailService } from '../email';
const result = await EmailService.sendEmail({
to: '[email protected]',
subject: 'Welcome to DeployStack',
template: 'welcome',
variables: {
userName: 'John Doe',
userEmail: '[email protected]',
loginUrl: 'https://app.deploystack.io/login'
}
});
if (result.success) {
request.log.info('Email sent successfully');
} else {
request.log.error('Failed to send email:', result.error);
}
Type-Safe Helper Methods
Available Methods
sendWelcomeEmail(options)
- Welcome email for new userssendPasswordResetEmail(options)
- Password reset instructionssendNotificationEmail(options)
- General notifications
// Example usage
const result = await EmailService.sendWelcomeEmail({
to: '[email protected]',
userName: 'Jane Smith',
userEmail: '[email protected]',
loginUrl: 'https://app.deploystack.io/login'
});
Advanced Features
- Custom From Address: Override default sender information
- Multiple Recipients: Send to arrays of email addresses
- Attachments: Include files with emails
- CC/BCC: Additional recipient types supported
Template System
Available Templates
Template | Description | Required Variables |
---|---|---|
welcome | Welcome email for new users | userName , userEmail , loginUrl |
password-reset | Password reset instructions | userName , resetUrl , expirationTime |
notification | General notification template | title , message |
Template Variables
All templates have access to these common variables:
currentYear
: Current year (automatically injected)appName
: Application name (default: 'DeployStack')supportEmail
: Support email address (if provided)
Custom Templates
To create custom templates:
- Add new Pug template in
src/email/templates/
- Add TypeScript types in
src/email/types.ts
- Use with
EmailService.sendEmail()
Color Guidelines
When adding colors to email templates, follow the official DeployStack color system to maintain brand consistency. If you want to check what our primary colors are, visit the UI Design System page.
Utility Methods
Test SMTP Connection
const status = await EmailService.testConnection(request.log);
if (status.success) {
request.log.info('SMTP connection successful');
} else {
request.log.error('SMTP connection failed:', status.error);
}
Other Utilities
getSmtpStatus()
- Check SMTP configuration statusrefreshConfiguration()
- Reload SMTP configurationgetAvailableTemplates()
- Get list of available templatesvalidateTemplate()
- Validate template and variables
Error Handling
The email service provides comprehensive error handling with specific error messages for:
- SMTP configuration issues
- Missing templates
- Invalid email addresses
- Connection failures
Security & Performance
Security Features
- Passwords encrypted in global settings
- Secure connections (TLS/SSL) supported
- Template security with escaped variable injection
Performance Features
- Template caching after first compilation
- Connection pooling (max 5 concurrent connections)
- Rate limiting (5 emails per 20 seconds)
Common Usage Patterns
User Registration
Send welcome emails after user account creation.
Password Reset
Generate reset tokens and send secure reset links.
System Notifications
Alert users about deployments, system updates, or important events.
API Reference
EmailService Methods
Method | Description | Returns |
---|---|---|
sendEmail(options) | Send an email using a template | Promise<EmailSendResult> |
sendWelcomeEmail(options) | Send a welcome email | Promise<EmailSendResult> |
sendPasswordResetEmail(options) | Send a password reset email | Promise<EmailSendResult> |
sendNotificationEmail(options) | Send a notification email | Promise<EmailSendResult> |
testConnection() | Test SMTP connection | Promise<{success: boolean, error?: string}> |
getSmtpStatus() | Check SMTP configuration status | Promise<{configured: boolean, error?: string}> |
refreshConfiguration() | Reload SMTP configuration | Promise<void> |
getAvailableTemplates() | Get list of available templates | string[] |
validateTemplate(template, variables) | Validate template and variables | Promise<TemplateValidationResult> |
TemplateRenderer Methods
Method | Description | Returns |
---|---|---|
render(options) | Render a template with variables | Promise<string> |
validateTemplate(template, variables) | Validate template | Promise<TemplateValidationResult> |
getAvailableTemplates() | Get available templates | string[] |
clearCache() | Clear template cache | void |
getTemplateMetadata(template) | Get template metadata | {description?: string, requiredVariables?: string[]} |
For more information about global settings configuration, see Global Settings.
Backend Logging & Log Level Configuration
Complete guide to configuring and using log levels in the DeployStack backend for development and production environments.
OAuth Provider Implementation
Developer guide for implementing third-party OAuth providers (GitHub, Google, etc.) for user authentication in DeployStack