Enterprise-grade temporary email service with custom SMTP server implementation, real-time message delivery, and automated data lifecycle management. Built with Next.js 15, TypeScript, and PostgreSQL.
- Overview
- System Architecture
- Security Model
- Features
- Technology Stack
- Prerequisites
- Installation
- Configuration
- Deployment
- API Documentation
- Security Audit
- Performance
- Monitoring
- Contributing
- License
A production-ready temporary email service providing disposable email addresses with automatic expiration. The system implements a complete mail transfer agent (MTA) with SMTP server, RESTful API, and modern web interface.
- Instant Mailbox Provisioning: Zero-registration email address generation
- Custom SMTP Implementation: Full RFC 5321-compliant mail server
- Automated Data Lifecycle: Time-based expiration with scheduled cleanup
- Enterprise Security: Multi-layer protection including rate limiting, input validation, and domain restrictions
- Scalable Architecture: Designed for horizontal scaling and high availability
- Real-time Updates: Client-side polling with exponential backoff
┌─────────────────┐
│ Frontend │
│ (Next.js) │
└────────┬────────┘
│ HTTPS
▼
┌─────────────────┐
│ Reverse Proxy │
│ (Nginx) │
└────────┬────────┘
│
▼
┌─────────────────┐ ┌──────────────┐
│ API Server │◄────►│ PostgreSQL │
│ (Express) │ │ Database │
└─────────────────┘ └──────────────┘
▲
│
┌─────────────────┐
│ SMTP Server │
│ (Port 25) │
└─────────────────┘
▲
│ SMTP
┌─────────────────┐
│ Mail Clients │
└─────────────────┘
- Framework: Next.js 15 with App Router
- Rendering: Server-side rendering with React 19
- Styling: Tailwind CSS with custom design system
- Animations: GSAP for performant UI interactions
- Runtime: Node.js with Express framework
- Data Access: Prisma ORM for type-safe database operations
- Security: CORS protection, rate limiting, input validation
- Monitoring: Structured logging and health check endpoints
- Implementation: Custom SMTP server using smtp-server library
- Protocol: RFC 5321 Simple Mail Transfer Protocol
- Security: Domain validation, relay prevention, size limits
- Processing: Asynchronous message parsing and storage
- Engine: PostgreSQL 14+
- Schema Management: Prisma migrations
- Optimization: Strategic indexing on timestamp fields
- Connection: Pooled connections for efficiency
- Scheduler: Cron-based job execution
- Strategy: Cascade deletion of expired records
- Leadership: Single-leader election for multi-instance deployments
- Logging: Detailed cleanup metrics and reporting
- Public Access: No authentication required (by design)
- Email Ownership: Implicit through knowledge of email address
- Administrative Access: Not exposed via public API
- Username Sanitization: Whitelist approach (alphanumeric, hyphen, underscore, dot)
- Length Constraints: 1-64 characters for username
- Domain Validation: Strict matching against configured domain
- SQL Injection Prevention: Parameterized queries via Prisma ORM
| Endpoint Category | Limit | Window | Tracking Method |
|---|---|---|---|
| Mailbox Creation | 10 requests | 60 minutes | IP-based |
| Message Access | 100 requests | 60 seconds | IP-based |
| General API | 200 requests | 60 seconds | IP-based |
- Encryption in Transit: TLS 1.2+ for all HTTPS connections
- Encryption at Rest: Database-level encryption (deployment dependent)
- Data Minimization: No personally identifiable information collected
- Automatic Expiration: 24-hour time-to-live for all records
- Allowed Origins: Configurable whitelist via environment variables
- Credentials: Disabled by default
- Methods: GET, POST only
- Headers: Standard headers only
- HTML Sanitization: DOMPurify with restrictive configuration
- XSS Prevention: React automatic escaping
- Inline Scripts: Blocked in email content
- External Resources: Restricted via Content Security Policy
- SMTP Relay Prevention: Domain whitelist enforcement
- Reverse Proxy: X-Forwarded-For header trust
- Firewall: Ports 25, 80, 443 only
- DDoS Protection: Rate limiting at multiple layers
- Instant temporary email address generation
- Custom username selection with availability check
- Real-time email reception via SMTP
- HTML and plain text email rendering
- Attachment download support
- Automated 24-hour expiration
- Zero-registration workflow
- Single-page application architecture
- Responsive design for all device sizes
- Real-time inbox updates
- One-click email address copying
- Progressive web application capabilities
- Health check endpoints for monitoring
- Structured logging for audit trails
- Automated data lifecycle management
- Leader election for distributed cleanup
- Analytics integration (optional)
- Next.js 15.1.6
- React 19.0.0
- TypeScript 5.7.3
- Tailwind CSS 4.0.6
- GSAP 3.12.5 (animations)
- Lenis 1.1.17 (smooth scroll)
- Radix UI (accessible components)
- Node.js 20+
- Express 4.21.2
- TypeScript 5.7.3
- Prisma 6.12.0 (ORM)
- smtp-server 3.14.0
- mailparser 3.7.4
- express-rate-limit 7.5.0
- PostgreSQL 14+
- Nginx (reverse proxy)
- PM2 (process management)
- Let's Encrypt (SSL/TLS)
- tsx 4.19.2 (TypeScript execution)
- ESLint (code quality)
- Prettier (code formatting)
- Operating System: Linux (Ubuntu 22.04 LTS recommended)
- Node.js: Version 18.0.0 or higher
- PostgreSQL: Version 14.0 or higher
- Memory: Minimum 1GB RAM (2GB recommended)
- Storage: Minimum 20GB available space
- Port 25: Open for SMTP traffic (inbound)
- Port 80: Open for HTTP traffic (redirects)
- Port 443: Open for HTTPS traffic
- DNS Access: For domain validation and MX records
- Package Manager: pnpm 8+ (recommended) or npm 9+
- Git: Version control
- Text Editor: VS Code or similar with TypeScript support
git clone https://github.com/SheerWill007/temp-mail.git
cd temp-mailcd backend
pnpm installConfigure environment:
cp .env.example .env
# Edit .env with your configuration (see Configuration section)Database initialization:
pnpm prisma:generate
pnpm prisma migrate deploycd ../frontend
pnpm installConfigure environment:
cp .env.example .env.local
# Edit .env.local with API endpoint URLsStart backend (development):
cd backend
pnpm devStart frontend (separate terminal):
cd frontend
pnpm devAccess application: http://localhost:3000
Required environment variables must be set in backend/.env:
Database Configuration
DATABASE_URL: PostgreSQL connection string
Server Configuration
API_PORT: Port for Express server (default: 3001)SMTP_PORT: Port for SMTP server (25 for production, 2525 for development)
Domain Configuration
SMTP_DOMAIN: Domain for email addressesMAIL_DOMAIN: Alternative domain specification
Security Configuration
FRONTEND_URL: Allowed CORS originCORS_ORIGIN: Comma-separated list of allowed originsNODE_ENV: Environment mode (development|production)
Service Configuration
CLEANUP_ENABLED: Enable automated cleanup (true|false)CLEANUP_LEADER: Designate as cleanup leader (true|false)
Optional Configuration
POSTHOG_API_KEY: Analytics API keyRATE_LIMIT_WINDOW_MS: Rate limit window in millisecondsRATE_LIMIT_MAX: Maximum requests per window
Required environment variables must be set in frontend/.env.local:
API Configuration
NEXT_PUBLIC_API_BASE: Backend API URLNEXT_PUBLIC_SITE_URL: Frontend site URLNEXT_PUBLIC_MAIL_DOMAIN: Email domain for display
Optional Configuration
NEXT_PUBLIC_POSTHOG_KEY: Analytics public keyNEXT_PUBLIC_POSTHOG_HOST: Analytics host URL
- VPS Provider: DigitalOcean, AWS EC2, Linode, Hetzner, or Vultr
- Minimum Specifications: 1 vCPU, 2GB RAM, 20GB SSD
- Network: Public IP address, port 25 access for SMTP
# Update system packages
apt update && apt upgrade -y
# Install Node.js 20
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
# Install PostgreSQL
apt install -y postgresql postgresql-contrib
# Install process manager
npm install -g pm2 pnpmsudo -u postgres psqlCREATE DATABASE tempmail;
CREATE USER tempmail_user WITH ENCRYPTED PASSWORD '<secure-password>';
GRANT ALL PRIVILEGES ON DATABASE tempmail TO tempmail_user;
\q# Create application directory
mkdir -p /var/www/temp-mail
cd /var/www/temp-mail
# Clone repository
git clone <repository-url> .
# Deploy backend
cd backend
pnpm install --prod
cp .env.example .env
# Configure .env with production values
pnpm prisma:generate
pnpm prisma migrate deploy
pnpm build
# Start with PM2
pm2 start dist/index.js --name temp-mail-backend
pm2 save
pm2 startup# Install Nginx
apt install -y nginx
# Create configuration
nano /etc/nginx/sites-available/temp-mailNginx configuration:
server {
listen 80;
server_name yourdomain.com api.yourdomain.com;
location / {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}Enable configuration:
ln -s /etc/nginx/sites-available/temp-mail /etc/nginx/sites-enabled/
nginx -t
systemctl restart nginx# Install Certbot
apt install -y certbot python3-certbot-nginx
# Obtain certificate
certbot --nginx -d yourdomain.com -d api.yourdomain.com
# Verify auto-renewal
certbot renew --dry-run# Configure UFW
ufw allow 22/tcp # SSH
ufw allow 80/tcp # HTTP
ufw allow 443/tcp # HTTPS
ufw allow 25/tcp # SMTP
ufw enableConfigure the following DNS records:
A Records
yourdomain.com A <server-ip>
api.yourdomain.com A <server-ip>
MX Record
@ MX 10 yourdomain.com
SPF Record
@ TXT "v=spf1 ip4:<server-ip> -all"
cd frontend
pnpm build
# Deploy to Vercel
npx vercel --prodSet environment variables in Vercel dashboard per Configuration section.
Request
GET /api/health
Response (200 OK)
{
"ok": true
}Request
POST /api/mailboxes/custom
Content-Type: application/json
{
"username": "example"
}
Response (200 OK)
{
"address": "example@yourdomain.com",
"createdAt": "2024-01-15T10:30:00.000Z",
"expiresAt": "2024-01-16T10:30:00.000Z"
}Error Responses
- 400: Invalid username format or length
- 429: Rate limit exceeded
- 500: Internal server error
Request
POST /api/mailboxes/:address/messages
Response (200 OK)
{
"address": "example@yourdomain.com",
"createdAt": "2024-01-15T10:30:00.000Z",
"expiresAt": "2024-01-16T10:30:00.000Z",
"messageCount": 2,
"messages": [
{
"id": "clxxx1234567890",
"from": "sender@example.com",
"subject": "Test Message",
"preview": "This is a preview of the email content...",
"createdAt": "2024-01-15T11:00:00.000Z"
}
]
}Request
GET /api/messages/:id
Response (200 OK)
{
"id": "clxxx1234567890",
"from": "sender@example.com",
"subject": "Test Message",
"createdAt": "2024-01-15T11:00:00.000Z",
"mailbox": "example@yourdomain.com",
"parsedData": {
"subject": "Test Message",
"from": "sender@example.com",
"text": "Plain text content",
"html": "<html>...</html>",
"attachments": [],
"date": "2024-01-15T11:00:00.000Z"
}
}Request
GET /api/messages/:id/attachments/:index
Response (200 OK)
Content-Type: <mime-type>
Content-Disposition: attachment; filename="<filename>"
<binary-data>
-
Input Validation
- Status: Implemented
- Mechanism: Whitelist-based username sanitization
- Coverage: All user inputs
-
Rate Limiting
- Status: Implemented
- Mechanism: express-rate-limit with IP tracking
- Configuration: Multiple tiers per endpoint category
-
SQL Injection Prevention
- Status: Implemented
- Mechanism: Prisma ORM with parameterized queries
- Coverage: 100% of database operations
-
XSS Prevention
- Status: Implemented
- Mechanism: React automatic escaping + DOMPurify
- Coverage: All user-generated content
-
CORS Protection
- Status: Implemented
- Mechanism: Origin whitelist with strict validation
- Configuration: Environment-based
-
Data Lifecycle
- Status: Implemented
- Mechanism: Time-based expiration with automated cleanup
- Schedule: Hourly execution
-
SMTP Relay Prevention
- Status: Implemented
- Mechanism: Domain validation on RCPT TO
- Coverage: All incoming SMTP connections
-
Implement Request Logging
- Priority: High
- Description: Add comprehensive request/response logging for security audit trails
- Impact: Improved incident response capabilities
-
Add DKIM Signing
- Priority: Medium
- Description: Implement DomainKeys Identified Mail for outbound email authentication
- Impact: Improved email deliverability and authenticity
-
Implement Content-Security-Policy
- Priority: Medium
- Description: Add CSP headers to frontend responses
- Impact: Enhanced XSS protection
-
Add Database Encryption
- Priority: Medium
- Description: Enable PostgreSQL transparent data encryption
- Impact: Data protection at rest
-
Implement WAF Rules
- Priority: Low
- Description: Deploy Web Application Firewall for additional protection
- Impact: Defense against common attack patterns
- GDPR: Minimal data collection, automatic deletion, no tracking
- CCPA: No personal information sale, data minimization
- CAN-SPAM: Not applicable (receiving only)
Frontend Performance
- Server-side rendering for initial page load
- Code splitting at route level
- Image optimization via Next.js Image component
- Hardware-accelerated animations (GSAP)
- Prefetching of critical resources
Backend Performance
- Database connection pooling
- Indexed queries on timestamp fields
- Asynchronous request processing
- Efficient SMTP stream handling
- Response caching where applicable
Database Performance
- Strategic indexing on frequently queried fields
- Cascade deletion for referential integrity
- Regular VACUUM operations
- Connection pooling configuration
Target Response Times
- API Health Check: < 50ms
- Mailbox Creation: < 200ms
- Message List: < 300ms
- Message Detail: < 400ms
- Attachment Download: < 1s
Concurrent Users
- Supported: 1000+ simultaneous connections
- Rate Limited: As per configuration
Backend health endpoint:
curl https://api.yourdomain.com/api/healthExpected response:
{"ok": true}Structured logs location:
- Application:
/var/log/pm2/temp-mail-backend-out.log - Errors:
/var/log/pm2/temp-mail-backend-error.log - Nginx Access:
/var/log/nginx/access.log - Nginx Errors:
/var/log/nginx/error.log
Log format example:
[SMTP] Email received: user@domain.com
[API] Mailbox created: user@domain.com
[CLEANUP] Removed 42 expired messages
[RATE LIMIT EXCEEDED] IP: 192.168.1.1, Endpoint: /api/mailboxes/custom
PM2 monitoring:
pm2 monit
pm2 logs temp-mail-backend
pm2 statusPostgreSQL monitoring:
sudo -u postgres psql -c "SELECT count(*) FROM pg_stat_activity;"- Fork the repository
- Create a feature branch (
git checkout -b feature/description) - Implement changes with comprehensive testing
- Ensure code passes linting and type checking
- Commit with descriptive messages
- Push to your fork
- Submit a pull request with detailed description
- Follow TypeScript strict mode requirements
- Maintain ESLint compliance
- Document public APIs with JSDoc
- Write unit tests for business logic
- Ensure backwards compatibility
- Provide clear description of changes
- Reference related issues
- Include test coverage
- Update documentation as needed
- Request review from maintainers
This project is licensed under the MIT License. See LICENSE file for details.
For issues, questions, or contributions:
- GitHub Issues: https://github.com/SheerWill007/temp-mail/issues
- Repository: https://github.com/SheerWill007/temp-mail
Project Maintainer: WilliamBenLaw Last Updated: January 2025 Version: 1.0.0
