{"id":46064142,"url":"https://github.com/mail-os/mail","last_synced_at":"2026-03-01T12:01:50.945Z","repository":{"id":320491990,"uuid":"1082284654","full_name":"mail-os/mail","owner":"mail-os","description":"A performant \u0026 secure SMTP server implementation, designed for self-hosting email infrastructure.","archived":false,"fork":false,"pushed_at":"2026-02-26T03:51:54.000Z","size":6106,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-26T06:50:18.562Z","etag":null,"topics":["cli","imap","library","mail-server","pop3","smtp-server","zig"],"latest_commit_sha":null,"homepage":"","language":"Zig","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mail-os.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/SECURITY_AUDIT.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-24T02:33:07.000Z","updated_at":"2026-02-26T03:51:58.000Z","dependencies_parsed_at":"2026-02-07T04:00:34.486Z","dependency_job_id":null,"html_url":"https://github.com/mail-os/mail","commit_stats":null,"previous_names":["home-lang/mail","mail-os/mail"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/mail-os/mail","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mail-os%2Fmail","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mail-os%2Fmail/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mail-os%2Fmail/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mail-os%2Fmail/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mail-os","download_url":"https://codeload.github.com/mail-os/mail/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mail-os%2Fmail/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29969243,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-01T11:43:06.159Z","status":"ssl_error","status_checked_at":"2026-03-01T11:43:03.887Z","response_time":124,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","imap","library","mail-server","pop3","smtp-server","zig"],"created_at":"2026-03-01T12:01:50.326Z","updated_at":"2026-03-01T12:01:50.935Z","avatar_url":"https://github.com/mail-os.png","language":"Zig","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SMTP Server in Zig\n\n[![CI](https://github.com/yourusername/mail/workflows/CI/badge.svg)](https://github.com/yourusername/mail/actions)\n[![codecov](https://codecov.io/gh/yourusername/mail/branch/main/graph/badge.svg)](https://codecov.io/gh/yourusername/mail)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![Zig](https://img.shields.io/badge/Zig-0.15.1-orange.svg)](https://ziglang.org/)\n\nA performant and secure SMTP server implementation written in Zig, designed for self-hosting email infrastructure.\n\n## Features\n\n### Core SMTP\n\n- **RFC 5321 Compliant**: Full implementation of the core SMTP protocol\n- **Concurrent Connection Handling**: Multi-threaded design for handling multiple simultaneous connections\n- **ESMTP Extensions**:\n  - SIZE - Message size declaration\n  - 8BITMIME - 8-bit MIME transport\n  - PIPELINING - Command pipelining\n  - AUTH - Authentication mechanisms (PLAIN, LOGIN)\n  - STARTTLS - TLS encryption framework (ready for certificates)\n\n### Enterprise Features\n\n- **Multi-Tenancy Support**: Complete tenant isolation and resource management\n  - Four tenant tiers (Free, Starter, Professional, Enterprise)\n  - Per-tenant resource limits (users, domains, storage, messages)\n  - Feature flags per tenant tier\n  - Usage tracking and monitoring\n  - REST API for tenant management\n  - See [docs/MULTI_TENANCY.md](docs/MULTI_TENANCY.md)\n\n- **Cluster Mode for High Availability**: Distributed coordination and failover\n  - Leader election and automatic failover\n  - Distributed state management\n  - Node health monitoring\n  - Load balancing support\n  - 3+ node clusters recommended\n  - See [docs/CLUSTER_MODE.md](docs/CLUSTER_MODE.md)\n\n### Security \u0026 Rate Limiting\n\n- **Per-IP Rate Limiting**: Sliding window rate limiter with configurable limits\n  - Thread-safe implementation with mutex protection\n  - Automatic cleanup of stale entries\n  - Real-time rate limit statistics\n- **Connection Limits**: Maximum concurrent connections enforcement\n- **Max Recipients**: Configurable limit on recipients per message\n- **Email Validation**: RFC-compliant email address validation\n- **Input Sanitization**: Protection against injection attacks\n- **Security Event Logging**: Dedicated logging for security-related events\n\n### Configuration \u0026 Operations\n\n- **Command-Line Interface**: Comprehensive CLI with help and version flags\n  - `--port`, `--host` - Server binding configuration\n  - `--log-level` - Adjust logging verbosity (debug|info|warn|error|critical)\n  - `--max-connections` - Connection limit override\n  - `--enable-tls/--disable-tls` - TLS toggle\n  - `--enable-auth/--disable-auth` - Authentication toggle\n- **Environment Variables**: Full configuration via environment variables\n  - `SMTP_HOST`, `SMTP_PORT`, `SMTP_HOSTNAME`\n  - `SMTP_MAX_CONNECTIONS`, `SMTP_MAX_RECIPIENTS`\n  - `SMTP_MAX_MESSAGE_SIZE`\n  - `SMTP_ENABLE_TLS`, `SMTP_ENABLE_AUTH`\n  - `SMTP_TLS_CERT`, `SMTP_TLS_KEY`\n- **Graceful Shutdown**: SIGINT/SIGTERM handlers with connection draining\n- **Comprehensive Logging**: Multi-level structured logging\n  - File-based logging with timestamps\n  - Colored console output\n  - Thread-safe operations\n  - SMTP-specific logging methods\n\n### Performance \u0026 Storage\n\n- **Performance Optimized**: Built with Zig for minimal overhead\n  - Zero-cost abstractions\n  - Compile-time optimizations\n  - \u003c10MB memory footprint\n- **Maildir Storage**: Standard maildir format for message storage\n- **Connection Pooling**: Efficient resource management\n- **Active Connection Tracking**: Real-time monitoring of active sessions\n\n## Requirements\n\n- Zig 0.15.1 or later\n- POSIX-compliant system (Linux, macOS, BSD)\n\n## Building\n\n```bash\nzig build\n```\n\n## Running\n\n```bash\n# Run with defaults (0.0.0.0:2525)\nzig build run\n\n# Or run the compiled binary\n./zig-out/bin/smtp-server\n\n# Show help\n./zig-out/bin/smtp-server --help\n\n# Show version\n./zig-out/bin/smtp-server --version\n\n# Run on custom port with debug logging\n./zig-out/bin/smtp-server --port 587 --log-level debug\n\n# Run with custom configuration\n./zig-out/bin/smtp-server --host 127.0.0.1 --port 2525 --max-connections 200\n\n# Run with IPv6\n./zig-out/bin/smtp-server --host \"::1\" --port 2525\n\n# Bind to all IPv6 addresses\n./zig-out/bin/smtp-server --host \"::\" --port 2525\n\n# Using environment variables\nexport SMTP_PORT=2525\nexport SMTP_MAX_CONNECTIONS=500\nexport SMTP_HOSTNAME=\"mail.example.com\"\n./zig-out/bin/smtp-server\n\n# IPv6 via environment\nexport SMTP_HOST=\"::\"\n./zig-out/bin/smtp-server\n\n# Enable webhook notifications\nexport SMTP_WEBHOOK_URL=\"http://localhost:8080/webhook\"\n./zig-out/bin/smtp-server\n```\n\nThe server starts on `0.0.0.0:2525` by default (non-privileged port for development).\n\n**IPv6 Support**: The server fully supports IPv6. Use `::1` for localhost or `::` to bind to all IPv6 addresses.\n\n**Webhook Notifications**: Set `SMTP_WEBHOOK_URL` to receive HTTP POST notifications with JSON payload containing sender, recipients, size, and timestamp when mail is received.\n\nSee [EXAMPLES.md](EXAMPLES.md) for more usage examples including Docker, systemd, and production deployments.\n\n## Configuration\n\nConfiguration is managed in `src/config.zig`. Key settings include:\n\n- **host**: Bind address (default: \"0.0.0.0\")\n- **port**: Port number (default: 2525)\n- **max_connections**: Maximum concurrent connections (default: 100)\n- **enable_tls**: Enable STARTTLS support (default: false)\n- **tls_cert_path**: Path to TLS certificate\n- **tls_key_path**: Path to TLS private key\n- **enable_auth**: Require authentication (default: true)\n- **max_message_size**: Maximum message size in bytes (default: 10MB)\n- **timeout_seconds**: Connection timeout (default: 300s)\n- **rate_limit_per_ip**: Max messages per IP per hour (default: 100)\n- **hostname**: Server hostname (default: \"localhost\")\n- **webhook_url**: HTTP URL to POST on incoming mail (default: none)\n- **webhook_enabled**: Enable webhook notifications (default: false)\n\n## Testing\n\n### Zig Unit Tests\n\n```bash\n# Run Zig unit tests\nzig build test\n```\n\nThe project includes comprehensive unit tests for:\n- **Security Module**: Email validation, rate limiting, hostname validation\n- **Error Module**: SMTP error code mapping and error handling\n- **Config Module**: Configuration structure and validation\n\n### Integration Test Suite\n\n```bash\n# Run the automated SMTP integration tests\n./test-smtp.sh\n\n# Test against custom host/port\nSMTP_HOST=localhost SMTP_PORT=2525 ./test-smtp.sh\n```\n\nThe integration test suite includes 20 comprehensive tests:\n- Basic SMTP commands (HELO/EHLO, MAIL FROM, RCPT TO, DATA)\n- Authentication testing\n- Rate limiting verification\n- Maximum recipients enforcement\n- Message size limit validation\n- Invalid command handling\n- Sequence validation\n- Case insensitivity\n\n### Manual Testing with telnet\n\n```bash\n# Using telnet\ntelnet localhost 2525\n\n# Example session:\nEHLO client.example.com\nMAIL FROM:\u003csender@example.com\u003e\nRCPT TO:\u003crecipient@example.com\u003e\nDATA\nSubject: Test Message\nFrom: sender@example.com\nTo: recipient@example.com\n\nThis is a test message.\n.\nQUIT\n```\n\n### Testing with swaks\n\n```bash\n# Using swaks (Swiss Army Knife for SMTP)\nswaks --to recipient@example.com \\\n      --from sender@example.com \\\n      --server localhost:2525 \\\n      --body \"Test message\"\n\n# Test with authentication\nswaks --to recipient@example.com \\\n      --from sender@example.com \\\n      --server localhost:2525 \\\n      --auth PLAIN \\\n      --auth-user test \\\n      --auth-password test\n\n# Test rate limiting (send multiple messages)\nfor i in {1..105}; do\n    swaks --to test@example.com \\\n          --from sender@example.com \\\n          --server localhost:2525 \\\n          --body \"Message $i\" \\\n          --hide-all\ndone\n```\n\nSee [EXAMPLES.md](EXAMPLES.md) for more testing examples and integration guides.\n\n## Project Structure\n\n```\n.\n├── build.zig           # Build configuration\n├── test-smtp.sh        # Automated test suite\n├── EXAMPLES.md         # Comprehensive usage examples\n├── TLS.md              # TLS/STARTTLS setup guide\n├── TODO.md             # Development roadmap\n├── src/\n│   ├── main.zig        # Entry point with CLI and signal handling\n│   ├── smtp.zig        # SMTP server with connection management\n│   ├── protocol.zig    # SMTP protocol handler (RFC 5321)\n│   ├── config.zig      # Configuration with env var support\n│   ├── args.zig        # Command-line argument parser\n│   ├── auth.zig        # Authentication mechanisms\n│   ├── security.zig    # Rate limiting, validation, security\n│   ├── logger.zig      # Multi-level structured logging\n│   ├── errors.zig      # Custom error types and handling\n│   ├── webhook.zig     # Webhook notifications\n│   └── tls.zig         # TLS certificate management\n└── mail/\n    └── new/            # Incoming messages (maildir format)\n```\n\n## Security Considerations\n\n### For Production Use\n\n1. **TLS/SSL**: Deploy behind a reverse proxy (nginx, HAProxy) for TLS termination:\n   ```bash\n   # See TLS.md for complete setup guide\n   # Example with nginx on port 465 (SMTPS)\n   # Server runs on port 2525, nginx handles TLS\n   ```\n\n   The server includes TLS configuration support but requires a reverse proxy for the cryptographic handshake. See [TLS.md](TLS.md) for detailed setup instructions including:\n   - nginx configuration with Let's Encrypt\n   - HAProxy setup\n   - Certificate management\n   - Self-signed certificates for development\n\n2. **Authentication**: The current implementation accepts all credentials. Implement proper credential verification in `src/auth.zig`:\n   ```zig\n   pub fn verifyCredentials(username: []const u8, password: []const u8) bool {\n       // Add your authentication logic here\n       // Check against database, LDAP, etc.\n   }\n   ```\n\n3. **Rate Limiting**: Adjust rate limits based on your needs in `config.zig`\n\n4. **Firewall**: Use firewall rules to restrict access:\n   ```bash\n   # Example using ufw\n   sudo ufw allow from trusted.ip.address to any port 25\n   ```\n\n5. **Run as Non-Root**: After binding to port 25, drop privileges:\n   ```bash\n   # Use a process supervisor like systemd with User= directive\n   ```\n\n6. **Logging**: Monitor logs for suspicious activity\n\n7. **SPF/DKIM/DMARC**: Implement email authentication when sending:\n   - Set up SPF records\n   - Configure DKIM signing\n   - Publish DMARC policy\n\n## Running on Port 25\n\nTo run on the standard SMTP port (25), you'll need elevated privileges:\n\n```bash\n# Option 1: Run as root (not recommended)\nsudo zig build run\n\n# Option 2: Grant capability (Linux)\nsudo setcap 'cap_net_bind_service=+ep' zig-out/bin/smtp-server\n./zig-out/bin/smtp-server\n\n# Option 3: Use iptables redirect\nsudo iptables -t nat -A PREROUTING -p tcp --dport 25 -j REDIRECT --to-port 2525\n```\n\n## Development\n\n### Running All Tests\n\n```bash\n# Run Zig unit tests\nzig build test\n\n# Run integration tests (requires server running on port 2525)\n./test-smtp.sh\n```\n\n### Code Style\n\nThis project follows Zig's standard formatting:\n\n```bash\nzig fmt src/\n```\n\n### Release Process\n\nThis project uses [zig-bump](https://github.com/stacksjs/zig-bump) for version management and automated releases.\n\n#### Quick Release (Recommended)\n\nThe easiest way - an interactive script that guides you through the release:\n\n```bash\n./scripts/release.sh\n# or\nmake release\n```\n\nThis provides a beautiful interactive menu with:\n- Pre-release checklist\n- Version selection with visual preview\n- Dry-run option\n- Confirmation before release\n- Automatic CHANGELOG.md reminder\n\n#### Direct Commands\n\nIf you prefer direct commands:\n\n```bash\n# Native Zig build (cross-platform)\nzig build bump-patch       # Bug fixes (0.0.1 -\u003e 0.0.2)\nzig build bump-minor       # New features (0.0.1 -\u003e 0.1.0)\nzig build bump-major       # Breaking changes (0.0.1 -\u003e 1.0.0)\nzig build bump             # Interactive selection\nzig build bump-patch-dry   # Preview changes\n\n# Or using Makefile shortcuts\nmake release-patch         # Same as zig build bump-patch\nmake release-minor         # Same as zig build bump-minor\nmake release-major         # Same as zig build bump-major\n```\n\nWhen you bump the version, it will:\n1. Update `build.zig.zon`\n2. Create a git commit and tag\n3. Push to GitHub\n4. Trigger the release workflow to build binaries and Docker images\n\nSee [docs/RELEASE_PROCESS.md](docs/RELEASE_PROCESS.md) for detailed release documentation.\n\n## Roadmap\n\n### Completed ✅\n- [x] Database-backed authentication\n- [x] DKIM signing support\n- [x] SPF validation\n- [x] Greylisting\n- [x] Spam filtering integration\n- [x] Webhook notifications for incoming mail\n- [x] REST API for message retrieval\n- [x] Web-based admin interface\n- [x] IPv6 support\n- [x] SMTP relay configuration\n- [x] Bounce handling\n- [x] Raft consensus for cluster mode\n- [x] Cluster mode integration\n- [x] Multi-tenancy support\n- [x] Secret management integration (Vault, K8s Secrets, AWS, Azure)\n- [x] Application metrics (StatsD integration)\n- [x] Alerting integration (Slack, PagerDuty, OpsGenie, webhooks)\n\n### In Progress 🚧\n- [ ] Full TLS/STARTTLS implementation (98% complete - cipher negotiation issue remains)\n\n### Recently Completed 🎉\n- [x] TOML configuration file support\n- [x] Hot configuration reload (SIGHUP)\n- [x] Distributed tracing exporters (Jaeger, DataDog, Zipkin, OTLP)\n- [x] io_uring integration for Linux\n- [x] IMAP server integration (IMAP4rev1, 24 commands)\n- [x] POP3 server integration\n- [x] WebSocket real-time notifications\n- [x] CalDAV/CardDAV support\n- [x] ActiveSync protocol support\n- [x] Machine learning spam detection\n- [x] Version consistency (central version module)\n- [x] Cluster health monitoring integration\n\n### Planned 📋\n- [ ] Full native TLS cipher negotiation\n- [ ] Additional ML model training pipelines\n\n## Performance\n\nBuilt with Zig's performance-first philosophy:\n\n- Zero-cost abstractions\n- Compile-time optimizations\n- Minimal runtime overhead\n- Efficient memory management\n- No garbage collection pauses\n\nTypical performance on modern hardware:\n- 1000+ concurrent connections\n- Sub-millisecond response times\n- \u003c10MB memory footprint for base server\n\n## Contributing\n\nContributions are welcome! Please ensure:\n\n1. Code follows Zig formatting (`zig fmt`)\n2. Tests pass (`zig build test`)\n3. Security considerations are addressed\n4. Documentation is updated\n\n## License\n\nMIT License - See LICENSE file for details\n\n## Acknowledgments\n\n- Built with [Zig](https://ziglang.org/)\n- SMTP protocol: [RFC 5321](https://tools.ietf.org/html/rfc5321)\n- ESMTP extensions: [RFC 1869](https://tools.ietf.org/html/rfc1869)\n\n## Support\n\nFor issues, questions, or contributions, please open an issue on the repository.\n\n## Project Status\n\n**Version**: v0.28.0 - **Enterprise Ready** 🚀\n\nAll core features plus enterprise capabilities are complete! See [PROJECT_STATUS.md](docs/PROJECT_STATUS.md) for:\n- Complete feature list and implementation status\n- Project metrics and statistics\n- Recent release notes\n- Production readiness checklist\n- Future roadmap\n\n### What's New in v0.28.0\n\n- **Performance**: Enhanced hot path optimizations and memory efficiency\n- **Reliability**: Improved error handling and recovery mechanisms\n- **Testing Infrastructure**: Comprehensive load testing and coverage improvements\n- **Code Quality**: Input validation and security hardening\n\n## Disclaimer\n\nThis SMTP server is production-ready with comprehensive features, security, and documentation. For specific deployment scenarios, refer to the deployment guides in the `docs/` directory.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmail-os%2Fmail","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmail-os%2Fmail","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmail-os%2Fmail/lists"}