Skip to main content
This example demonstrates how to build an SMTP server that requires authentication using PLAIN or LOGIN methods.

Complete example

auth-server.ts

Authentication flow

1

Client connects

The server sends a 220 greeting and advertises PLAIN and LOGIN in the EHLO response.
2

Client attempts TLS

Since allowInsecureAuth: false, the client must use STARTTLS before AUTH is allowed.
3

Client authenticates

The client sends AUTH PLAIN or AUTH LOGIN with credentials.
4

Server validates

The onAuth callback checks credentials and accepts or rejects.
5

Session continues

If authentication succeeds, session.user is set and the client can send mail.

Using the authenticated user

The user object you return in onAuth is available throughout the session:

Supporting multiple auth methods

See the Authentication guide for complete details on each auth method.

Rate limiting

Limit authentication attempts per IP:

Testing authentication

Test with openssl to see the SMTP dialogue:
Then:
Generate the PLAIN auth string:
Use Bun’s built-in btoa() and atob() functions to encode/decode base64 in your code.

Require TLS for authentication

The server rejects AUTH attempts over plain TCP when allowInsecureAuth: false:
Clients must use STARTTLS before sending AUTH commands.

Next steps

TLS configuration

Add STARTTLS and implicit TLS support

Authentication guide

Learn about CRAM-MD5 and XOAUTH2

Callbacks reference

Explore all lifecycle callbacks

Session object

Learn about the session object