LOG-001 // ENGINEERING
PUBLISHEDENGINEERING2025-07-28·8 min read
Building a Custom SMTP Server from Scratch
SMTPNode.jsDNSNetworking
When I started building Kosh, I knew from day one that I didn't want to rely on third-party email delivery services. I wanted full control over the mail pipeline — from the moment an email is composed to the second it lands in the recipient's inbox.
Why Build Your Own SMTP Server?
Most developers reach for services like SendGrid, Mailgun, or AWS SES. These are great for transactional emails, but Kosh isn't just sending emails — it IS the email platform. We needed to handle inbound mail, outbound delivery, custom domains, DKIM signing, SPF records, and DMARC policies all under one roof.
The Architecture
The SMTP server is built on Node.js using the net module for raw TCP socket handling. Here's the high-level flow:
1.Connection Handling — Accept incoming SMTP connections on port 25/587
2.EHLO/HELO Handshake — Negotiate capabilities including STARTTLS
3.Authentication — Validate credentials against our user database
4.Mail Transaction — Process MAIL FROM, RCPT TO, and DATA commands
5.Queue & Deliver — Push to a Redis-backed queue for async delivery
DNS Configuration
For each custom domain on Kosh, we automatically provision:
—MX Records — Point incoming mail to our servers
—SPF Records — Authorize our IPs to send on behalf of the domain
—DKIM Keys — Generate 2048-bit RSA key pairs for message signing
—DMARC Policies — Set up reporting and enforcement policies
Scaling Challenges
The biggest challenge was handling concurrent connections efficiently. Node.js's event loop is great for I/O-bound work, but we had to be careful about:
—Connection pooling for outbound SMTP relay
—Rate limiting per domain to avoid being flagged as spam
—Graceful handling of temporary failures with exponential backoff
—Memory management for large attachments streaming through the pipeline
Lessons Learned
Building an SMTP server taught me more about networking, DNS, and email standards (RFC 5321, RFC 6376) than any course ever could. The email ecosystem is surprisingly complex — but that complexity is what makes Kosh's from-scratch approach so powerful.
NODE: LOG-001 // TYPE: ARTICLEWORDS: ~343