@454creative/easy-email
Version:
A framework-agnostic email service library for Node.js with observability and monitoring
367 lines (283 loc) โข 9.33 kB
Markdown
# @454creative/easy-email
[](https://badge.fury.io/js/%40454creative%2Feasy-email)
[](https://opensource.org/licenses/ISC)
[](https://nodejs.org/)
A framework-agnostic email service library for Node.js with observability and monitoring capabilities. Supports SMTP, SendGrid, and AWS SES providers with comprehensive error handling, performance monitoring, and template rendering.
## ๐ Features
- **Framework Agnostic**: Works with any Node.js framework (Express, NestJS, Fastify, etc.)
- **Multiple Providers**: Support for SMTP, SendGrid, and AWS SES
- **Observability**: Built-in monitoring, logging, and metrics
- **Type Safety**: Full TypeScript support with comprehensive type definitions
- **Error Handling**: Robust error handling with detailed error information
- **Performance Monitoring**: Track email sending performance and identify bottlenecks
- **Template Engine**: HTML template rendering with variable substitution
- **Validation**: Email address validation and request validation
- **Retry Logic**: Automatic retry with exponential backoff
- **Rate Limiting**: Built-in rate limiting support
- **AWS SES Integration**: Full AWS SES support with advanced features
## ๐ฆ Installation
```bash
npm install @454creative/easy-email
```
## ๐ง Quick Start
### Basic Usage
```typescript
import { EmailService, EmailProviderType } from '@454creative/easy-email';
// Configure with SMTP
const emailService = new EmailService({
type: EmailProviderType.SMTP,
config: {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'your-email@gmail.com',
pass: 'your-password'
}
}
});
// Or configure with SendGrid
const sendGridService = new EmailService({
type: EmailProviderType.SENDGRID,
config: {
apiKey: 'your-sendgrid-api-key'
}
});
// Send email
const result = await emailService.sendEmail({
to: 'recipient@example.com',
subject: 'Hello from Easy Email!',
text: 'This is a test email',
from: 'sender@example.com'
});
if (result.success) {
console.log('Email sent successfully!');
} else {
console.error('Failed to send email:', result.error);
}
```
### SendGrid Configuration
```typescript
import { EmailService, EmailProviderType } from '@454creative/easy-email';
const emailService = new EmailService({
type: EmailProviderType.SENDGRID,
config: {
apiKey: 'your-sendgrid-api-key'
}
});
```
### AWS SES Configuration
```typescript
import { EmailService, EmailProviderType, EmailConfigBuilder } from '@454creative/easy-email';
// Method 1: Using EmailConfigBuilder (Recommended)
const config = new EmailConfigBuilder(EmailProviderType.SES)
.withSesConfig({
region: 'us-west-2',
// Credentials will be loaded from environment variables:
// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
})
.withRetryAttempts(3)
.withTimeout(10000)
.build();
const emailService = new EmailService(config, {
email: 'noreply@yourdomain.com',
name: 'Your App'
});
// Method 2: Direct configuration
const sesConfig = {
type: EmailProviderType.SES,
config: {
region: 'us-west-2',
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
sessionToken: process.env.AWS_SESSION_TOKEN, // Optional
},
};
const emailService2 = new EmailService(sesConfig, {
email: 'noreply@yourdomain.com',
name: 'Your App'
});
```
## ๐ API Reference
### Available Exports
```typescript
import {
// Main services
EmailService,
ObservabilityService,
SesService,
// Enums and constants
EmailProviderType,
EMAIL_CONSTANTS,
OBSERVABILITY_CONSTANTS,
// Performance utilities
PerformanceMonitor,
trackPerformance,
// Version information
VERSION,
LIBRARY_INFO,
// Error classes
EmailServiceError,
ConfigurationError,
ProviderError,
ValidationError,
// Utility functions
validateEmail,
isValidEmail,
checkEmailTypos
} from '@454creative/easy-email';
```
### EmailService
The main service class for sending emails.
#### Constructor
```typescript
new EmailService(
providerConfig: EmailProviderConfig | SmtpConfig,
defaultFrom?: { email: string; name?: string },
observabilityConfig?: ObservabilityConfig
)
```
#### Methods
- `sendEmail(request: EmailRequest): Promise<EmailResponse>` - Send an email
- `verifyConnection(): Promise<boolean>` - Verify provider connection
- `sendPlainText(to, subject, text, options?): Promise<EmailResponse>` - Send plain text email
- `sendHtml(to, subject, html, options?): Promise<EmailResponse>` - Send HTML email
### Interfaces
#### EmailRequest
```typescript
interface EmailRequest {
to: string | string[];
subject: string;
text?: string;
html?: string;
from?: string;
cc?: string | string[];
bcc?: string | string[];
replyTo?: string;
attachments?: EmailRequestAttachment[];
headers?: Record<string, string>;
}
```
#### EmailProviderType
```typescript
enum EmailProviderType {
SMTP = 'smtp',
SENDGRID = 'sendgrid',
SES = 'ses'
}
```
#### EmailResponse
```typescript
interface EmailResponse {
success: boolean;
messageId?: string;
error?: {
message: string;
code?: string;
provider?: string;
details?: any;
};
}
```
## ๐ Observability
The library includes built-in observability features:
```typescript
import { ObservabilityService } from '@454creative/easy-email';
const observability = ObservabilityService.getInstance({
enabled: true,
logLevel: 'info',
trackMetrics: true
});
// Get metrics
const metrics = observability.getMetrics();
console.log('Email metrics:', metrics);
```
## ๐ฏ Performance Monitoring
Track performance with the built-in performance monitor:
```typescript
import { PerformanceMonitor } from '@454creative/easy-email';
const monitor = PerformanceMonitor.getInstance({
enabled: true,
thresholdMs: 1000,
logSlowOperations: true
});
// Get performance summary
const summary = monitor.getSummary();
console.log('Performance summary:', summary);
```
## ๐ ๏ธ Error Handling
The library provides comprehensive error handling:
```typescript
import {
EmailServiceError,
ValidationError,
ProviderError
} from '@454creative/easy-email';
try {
const result = await emailService.sendEmail(request);
// Handle success
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof ProviderError) {
console.error('Provider error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
```
## ๐ Examples
See the `examples/` directory for comprehensive examples:
- [Simple Best Practice](./examples/simple-best-practice.ts)
- [SendGrid Example](./examples/sendgrid-example.ts)
- [AWS SES Example](./examples/ses-example.ts)
- [Observability Example](./examples/observability-example.ts)
- [Event-Driven Example](./examples/event-driven-example.ts)
- [SendGrid Debugging](./examples/sendgrid-debugging-example.ts)
For detailed documentation and guides, see the [Documentation Directory](./documentation/).
## ๐ Documentation
### AWS SES Integration
- [AWS SES Setup Guide](./documentation/aws-ses-setup.md) - Complete setup instructions
- [AWS SES Examples](./documentation/aws-ses-examples.md) - Comprehensive usage examples
- [AWS SES Troubleshooting](./documentation/aws-ses-troubleshooting.md) - Common issues and solutions
### General Documentation
- [Getting Started](./documentation/getting-started.md) - Quick start guide
- [API Reference](./documentation/api-reference.md) - Complete API documentation
- [Best Practices](./documentation/best-practices.md) - Development guidelines
- [Troubleshooting](./documentation/troubleshooting.md) - Common issues and solutions
## ๐งช Testing
```bash
# Run all tests
npm test
# Run unit tests
npm run test:unit
# Run integration tests
npm run test:integration
# Run with coverage
npm run test:coverage
```
## ๐ Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ License
This project is licensed under the ISC License - see the [LICENSE](LICENSE) file for details.
## ๐ค Support
- **Issues**: [GitHub Issues](https://bitbucket.org/454creative/easy-email/issues)
- **Documentation**: [Documentation Directory](./documentation/)
- **API Reference**: [Generated API Docs](./docs/)
- **Examples**: [Examples Directory](./examples/)
## ๐ Changelog
See [CHANGELOG.md](CHANGELOG.md) for a complete list of changes, version history, and migration guides.
## ๐ Roadmap
- [x] AWS SES integration โ
- [ ] Additional email providers (Mailgun)
- [ ] Advanced template engine with layouts
- [ ] Email scheduling and queuing
- [ ] Webhook support for delivery tracking
- [ ] Advanced rate limiting strategies
- [ ] Email analytics and reporting
---
**Made with โค๏ธ by [454 Creative](https://454creative.com)**