297 lines
9.1 KiB
Markdown
297 lines
9.1 KiB
Markdown
# WildDuck Mail Server Gateway
|
|
|
|
A comprehensive NestJS gateway for interacting with the [WildDuck Email Server](https://wildduck.email/) HTTP API. This gateway provides a clean, type-safe interface for managing email accounts, messages, mailboxes, and all other WildDuck features.
|
|
|
|
## Features
|
|
|
|
- **Complete WildDuck API Coverage**: All major WildDuck API endpoints are implemented
|
|
- **Type Safety**: Full TypeScript support with comprehensive DTOs and interfaces
|
|
- **NestJS Best Practices**: Follows enterprise-grade patterns and conventions
|
|
- **Modular Architecture**: Clean separation of concerns with dedicated services
|
|
- **Swagger Documentation**: Auto-generated API documentation
|
|
- **Error Handling**: Robust error handling and logging
|
|
- **Observables**: RxJS-based reactive programming for better async handling
|
|
- **Configuration**: Environment-based configuration management
|
|
|
|
## API Coverage
|
|
|
|
### User Management
|
|
|
|
- Create, read, update, delete users
|
|
- User authentication and authorization
|
|
- Password management and reset
|
|
- User quota management
|
|
- Authentication logs
|
|
|
|
### Email Messages
|
|
|
|
- List, search, and filter messages
|
|
- Send, receive, and manage messages
|
|
- Message attachments handling
|
|
- Draft management
|
|
- Message forwarding
|
|
- Bulk operations
|
|
|
|
### Mailboxes
|
|
|
|
- Create and manage mail folders
|
|
- Mailbox permissions and settings
|
|
- Message counts and statistics
|
|
- Mailbox retention policies
|
|
|
|
### Email Addresses
|
|
|
|
- Manage user email addresses and aliases
|
|
- Primary address configuration
|
|
- Address validation
|
|
|
|
### Filters and Rules
|
|
|
|
- Create email filters and rules
|
|
- Automatic message processing
|
|
- Spam filtering
|
|
- Custom actions and conditions
|
|
|
|
### Authentication & Security
|
|
|
|
- Two-factor authentication (TOTP)
|
|
- Application-specific passwords
|
|
- Session management
|
|
- Security logging
|
|
|
|
### Advanced Features
|
|
|
|
- Auto-replies and out-of-office messages
|
|
- Message archiving and restoration
|
|
- Audit trails and logging
|
|
- Webhook integrations
|
|
|
|
## Installation & Setup
|
|
|
|
### 1. Install Dependencies
|
|
|
|
This gateway is already integrated into your existing NestJS project. The required dependencies are:
|
|
|
|
```bash
|
|
npm install @nestjs/axios axios rxjs
|
|
```
|
|
|
|
### 2. Environment Configuration
|
|
|
|
Add the following environment variables to your `.env` file:
|
|
|
|
```env
|
|
# WildDuck Mail Server Configuration
|
|
WILDDUCK_BASE_URL=http://localhost:8080
|
|
WILDDUCK_ACCESS_TOKEN=your-access-token-here
|
|
WILDDUCK_TIMEOUT=30000
|
|
WILDDUCK_RETRIES=3
|
|
```
|
|
|
|
### 3. Module Import
|
|
|
|
The `MailServerModule` is already imported in your `AppModule`. The gateway is ready to use!
|
|
|
|
## Usage Examples
|
|
|
|
### Basic User Operations
|
|
|
|
```typescript
|
|
import { MailServerService } from "./modules/mail-server/services/mail-server.service";
|
|
|
|
@Injectable()
|
|
export class EmailService {
|
|
constructor(private readonly mailServer: MailServerService) {}
|
|
|
|
// Create a complete email account
|
|
async createEmailAccount(username: string, password: string, email: string) {
|
|
return this.mailServer
|
|
.createEmailAccount({
|
|
username,
|
|
password,
|
|
email,
|
|
name: "User Name",
|
|
quota: 1073741824, // 1GB
|
|
})
|
|
.toPromise();
|
|
}
|
|
|
|
// Authenticate user and get profile
|
|
async authenticateUser(username: string, password: string) {
|
|
return this.mailServer.authenticateAndGetUser(username, password).toPromise();
|
|
}
|
|
|
|
// Get user's mailboxes with message counts
|
|
async getUserMailboxes(userId: string) {
|
|
return this.mailServer.getUserMailboxes(userId).toPromise();
|
|
}
|
|
}
|
|
```
|
|
|
|
### Advanced Message Operations
|
|
|
|
```typescript
|
|
// Search messages across all folders
|
|
async searchUserMessages(userId: string, query: string) {
|
|
return this.mailServer.searchAllMessages(userId, query, 50).toPromise();
|
|
}
|
|
|
|
// Send a message
|
|
async sendMessage(userId: string, mailboxId: string, rawMessage: string) {
|
|
return this.mailServer.sendMessage(userId, mailboxId, {
|
|
raw: rawMessage,
|
|
seen: false,
|
|
flagged: false
|
|
}).toPromise();
|
|
}
|
|
|
|
// Get recent messages
|
|
async getRecentMessages(userId: string, mailboxId: string) {
|
|
return this.mailServer.getRecentMessages(userId, mailboxId, 20).toPromise();
|
|
}
|
|
```
|
|
|
|
### Direct Service Access
|
|
|
|
For more granular control, you can access individual services directly:
|
|
|
|
```typescript
|
|
@Injectable()
|
|
export class DetailedEmailService {
|
|
constructor(private readonly mailServer: MailServerService) {}
|
|
|
|
// Direct access to specific services
|
|
async createUser(userData: CreateUserDto) {
|
|
return this.mailServer.users.createUser(userData).toPromise();
|
|
}
|
|
|
|
async listMessages(userId: string, mailboxId: string, options: ListMessagesQueryDto) {
|
|
return this.mailServer.messages.listMessages(userId, mailboxId, options).toPromise();
|
|
}
|
|
|
|
async createFilter(userId: string, filterData: CreateFilterDto) {
|
|
return this.mailServer.filters.createFilter(userId, filterData).toPromise();
|
|
}
|
|
|
|
async setup2FA(userId: string, issuer: string) {
|
|
return this.mailServer.auth.setup2FA(userId, { issuer }).toPromise();
|
|
}
|
|
}
|
|
```
|
|
|
|
## API Endpoints
|
|
|
|
The gateway exposes REST endpoints under `/mail-server`:
|
|
|
|
### User Management
|
|
|
|
- `GET /mail-server/users` - List users
|
|
- `POST /mail-server/users` - Create user
|
|
- `GET /mail-server/users/:userId` - Get user details
|
|
- `PUT /mail-server/users/:userId` - Update user
|
|
- `DELETE /mail-server/users/:userId` - Delete user
|
|
|
|
### Authentication
|
|
|
|
- `POST /mail-server/authenticate` - Authenticate user
|
|
- `POST /mail-server/users/:userId/2fa/totp/setup` - Setup 2FA
|
|
- `POST /mail-server/users/:userId/2fa/totp/enable` - Enable 2FA
|
|
|
|
### Messages
|
|
|
|
- `GET /mail-server/users/:userId/mailboxes/:mailboxId/messages` - List messages
|
|
- `POST /mail-server/users/:userId/mailboxes/:mailboxId/messages` - Upload message
|
|
- `GET /mail-server/users/:userId/search` - Search messages
|
|
- `GET /mail-server/users/:userId/flagged` - List flagged messages
|
|
|
|
### Mailboxes
|
|
|
|
- `GET /mail-server/users/:userId/mailboxes` - List mailboxes
|
|
- `POST /mail-server/users/:userId/mailboxes` - Create mailbox
|
|
- `PUT /mail-server/users/:userId/mailboxes/:mailboxId` - Update mailbox
|
|
|
|
### High-Level Operations
|
|
|
|
- `POST /mail-server/accounts` - Create complete email account
|
|
- `POST /mail-server/auth-and-profile` - Authenticate and get profile
|
|
- `GET /mail-server/users/:userId/mailboxes-with-counts` - Get mailboxes with counts
|
|
|
|
## Architecture
|
|
|
|
The gateway follows a clean, modular architecture:
|
|
|
|
```
|
|
src/modules/mail-server/
|
|
├── dto/ # Data Transfer Objects
|
|
│ ├── create-user.dto.ts
|
|
│ ├── update-user.dto.ts
|
|
│ ├── authenticate.dto.ts
|
|
│ ├── message.dto.ts
|
|
│ ├── mailbox.dto.ts
|
|
│ ├── address.dto.ts
|
|
│ └── filter.dto.ts
|
|
├── interfaces/ # TypeScript interfaces
|
|
│ └── wildduck-response.interface.ts
|
|
├── services/ # Service layer
|
|
│ ├── wildduck-base.service.ts # Base HTTP service
|
|
│ ├── wildduck-users.service.ts # User management
|
|
│ ├── wildduck-messages.service.ts # Message operations
|
|
│ ├── wildduck-mailboxes.service.ts # Mailbox management
|
|
│ ├── wildduck-addresses.service.ts # Address management
|
|
│ ├── wildduck-auth.service.ts # Authentication
|
|
│ ├── wildduck-filters.service.ts # Filter management
|
|
│ └── mail-server.service.ts # Main orchestrator
|
|
├── mail-server.controller.ts # REST endpoints
|
|
└── mail-server.module.ts # Module definition
|
|
```
|
|
|
|
### Service Hierarchy
|
|
|
|
1. **WildDuckBaseService**: Provides common HTTP client functionality, error handling, and response processing
|
|
2. **Specialized Services**: Each service handles a specific domain (users, messages, etc.)
|
|
3. **MailServerService**: High-level service that orchestrates operations across multiple specialized services
|
|
4. **MailServerController**: REST API endpoints for external access
|
|
|
|
## Error Handling
|
|
|
|
The gateway includes comprehensive error handling:
|
|
|
|
- **HTTP Errors**: Automatic retry logic and timeout handling
|
|
- **WildDuck API Errors**: Proper error parsing and re-throwing
|
|
- **Validation Errors**: DTO validation with class-validator
|
|
- **Logging**: Detailed logging for debugging and monitoring
|
|
|
|
## Best Practices
|
|
|
|
1. **Use High-Level Methods**: Prefer `MailServerService` methods for common operations
|
|
2. **Handle Observables**: Convert to Promises with `.toPromise()` if needed
|
|
3. **Error Handling**: Always wrap calls in try-catch blocks
|
|
4. **Type Safety**: Use the provided DTOs for type safety
|
|
5. **Environment Variables**: Keep WildDuck credentials secure
|
|
|
|
## Swagger Documentation
|
|
|
|
The gateway automatically generates Swagger documentation. Access it at:
|
|
|
|
- Development: `http://localhost:3000/api`
|
|
- Production: `https://your-domain.com/api`
|
|
|
|
## Contributing
|
|
|
|
1. Follow the existing code patterns and architecture
|
|
2. Add proper TypeScript types and DTOs
|
|
3. Include comprehensive error handling
|
|
4. Add Swagger documentation for new endpoints
|
|
5. Write tests for new functionality
|
|
|
|
## WildDuck Server Setup
|
|
|
|
This gateway requires a running WildDuck mail server. For setup instructions, visit:
|
|
|
|
- [WildDuck Documentation](https://wildduck.email/)
|
|
- [GitHub Repository](https://github.com/nodemailer/wildduck)
|
|
|
|
## License
|
|
|
|
This project follows the same license as your main application.
|