Gumdrop provides a complete SMTP implementation for both server and client roles. The server supports RFC 5321 (SMTP) and RFC 6409 (Message Submission) with full ESMTP extensions. Like all Gumdrop protocols, the SMTP implementation is event-driven and non-blocking, achieving high performance with minimal resource consumption.
The SMTP server follows an "event-driven first" design philosophy. Rather than allocating a thread per connection - a model that limits scalability to the thousands - Gumdrop multiplexes all SMTP connections across a small pool of worker threads using Java NIO selectors. This approach has been proven in production since 2005 and enables a single server to handle tens of thousands of concurrent connections.
The protocol is modelled as a sequence of stages. At each stage the application is handed a handler interface that receives only the commands that are legal at that point, together with a state object that can accept or reject the command. Out-of-order replies cannot be written, because the method for the next stage only exists on the state object returned for the current one:
State transitions are validated strictly according to RFC 5321, with appropriate error responses for out-of-sequence commands.
Message content during the DATA phase is processed as a stream without buffering
the entire message in memory. The protocol handles dot-stuffing, CRLF
normalisation, and termination detection (CRLF.CRLF) incrementally
as data arrives, allowing arbitrarily large messages to be processed efficiently.
Gumdrop separates protocol mechanics from business logic. Your handler
receives high-level events about the session and makes policy decisions
without dealing with protocol syntax, reply codes or network I/O. A server is
assembled with SmtpServer.compose(), which takes one or more
listeners and a session provider: a factory that returns a fresh
ClientConnected handler for every connection, so per-connection
state needs no locking.
SmtpServer server = SmtpServer.compose()
.listener(new SmtpListener().port(2525))
.sessionProvider(provider)
.maxMessageSize(10L * 1024 * 1024)
.maxRecipients(50)
.server();
Gumdrop gumdrop = Gumdrop.boot();
gumdrop.addServer(server);
gumdrop.join();
A complete, compiled example lives in
examples/smtp-server/SmtpExample.java. It accepts mail for one
domain, refuses relaying, runs SPF, DKIM and DMARC checks and spools accepted
messages to a directory. The session provider is a small factory:
SmtpServerSessionProvider provider = new SmtpServerSessionProvider() {
@Override
public ClientConnected openSession(TcpListener listener) {
return new SpoolHandler(spoolDir);
}
};
For handlers that need no setup,
SmtpServerSessionProviders.perSession(Supplier) wraps a
supplier of ClientConnected in a provider.
One object can implement every stage, as the example does, or each stage can be a separate class. The methods are:
ClientConnected.connected(ConnectedState, Endpoint) - a
client connected; call acceptConnection(greeting, helloHandler)
(the first word of the greeting should be your domain, such as
mail.example.com ESMTP ready, because the server announces it in
its EHLO reply; without one the server uses its address as an address literal),
rejectConnection() or serverShuttingDown().
disconnected() is called when the connection closesHelloHandler.hello(HelloState, extended, hostname) -
HELO/EHLO received; acceptHello moves to the mail stage, or reject
it (rejectHello, rejectHelloTemporary,
rejectHelloAndClose)HelloHandler.tlsEstablished(SecurityInfo) - STARTTLS
completedHelloHandler.authenticated(AuthenticateState, Principal) -
AUTH succeeded; accept or reject itMailFromHandler.mailFrom(MailFromState, EmailAddress, smtputf8,
DeliveryRequirements) - sender evaluationMailFromHandler.getPipeline() - optionally supply an
SmtpPipeline for this transaction (see below)MailFromHandler.reset(ResetState) and quit() -
RSET and QUITRecipientHandler.rcptTo(RecipientState, EmailAddress,
MailboxFactory) - recipient validationRecipientHandler.startMessage(MessageStartState) - DATA or
BDAT initiationMessageDataHandler.messageContent(ByteBuffer) - streaming
message dataMessageDataHandler.messageComplete(MessageEndState) - the
whole message has arrived; accept or reject itMessageDataHandler.messageAborted() - the client went away
mid-message
A handler answers by calling a method on the state object it was given, and
it need not do so before returning. It can keep the state, consult an
external service (a database, a reputation list, a content filter) and
answer later without blocking the I/O thread. The connection holds back
further input until the reply has been sent. The reply must be made on the
connection's SelectorLoop thread, so a handler that did the work
elsewhere hands the answer back with
endpoint.getSelectorLoop().invokeLater(Runnable). The example
replies from a DNS callback, which already runs on that thread, because the
end of the message has to wait for the DMARC verdict:
@Override
public void messageComplete(MessageEndState state) {
pendingEnd = state;
finishMessage(); // replies now if the verdict is already in
}
For back-pressure, wantsPause() and
setResumeCallback(Runnable) on MessageDataHandler
let a handler that cannot keep up with the incoming data pause the read side
and resume it when it can.
The Endpoint passed to connected gives the remote
and local socket addresses, whether the connection is TLS-secured
(isSecure()) and its SecurityInfo (protocol, cipher
suite, peer certificates). tlsEstablished is called with the same
information after STARTTLS. The authenticated identity arrives in
authenticated as a Principal.
SmtpServerSessionProviders offers two ready-made providers for
simple cases:
relay() - a SimpleRelaySessionProvider that
accepts mail and forwards it to the recipient domain's MX hosts using
Gumdrop's SMTP client. It is an open relay: it accepts any sender to
any recipient with no authentication, so use it only for development, testing
and closed internal networks. Configure it with hostname,
server(address) or servers(...) (to bypass MX
lookup), deliveryPort, dnsResolver and
timeoutMslocalDelivery() - a LocalDeliverySessionProvider
that accepts mail for one localDomain and delivers it into
mailboxes through a MailboxFactory
SmtpServer server = SmtpServer.compose()
.listener(new SmtpListener().port(25))
.sessionProvider(SmtpServerSessionProviders.localDelivery()
.localDomain("example.com")
.hostname("mail.example.com")
.mailboxFactory(mailboxFactory))
.realm(realm)
.server();
Gumdrop provides a generic SmtpPipeline interface for processing
messages as they stream through the server. This enables pluggable processing
without modifying core SMTP code.
The pipeline receives notifications at key SMTP stages:
public interface SmtpPipeline {
void mailFrom(EmailAddress sender); // MAIL FROM received
void rcptTo(EmailAddress recipient); // RCPT TO received
WritableByteChannel getMessageChannel(); // Called at DATA start
void endData(); // Message complete
void reset(); // Transaction reset
}
A handler supplies a pipeline by returning it from
MailFromHandler.getPipeline(), which is called for each
transaction. While the pipeline is in place:
WritableByteChannel as they arriveendData() is called when the message ends, whether it was sent
with DATA or with BDAT, just before messageCompletereset() is called when the transaction ends, is reset or
the connection closesThis design supports various use cases:
The WritableByteChannel is a standard Java interface that clearly
expresses streaming semantics:
write(ByteBuffer) - receive message bytesclose() - signal end of streamisOpen() - check channel stateThis allows pipelines to process arbitrarily large messages without buffering the entire content in memory.
The org.bluezoo.gumdrop.smtp.auth package provides
AuthPipeline, an implementation of SmtpPipeline
that performs SPF, DKIM, and DMARC validation, with optional
RFC 8617 Authenticated
Received Chain (ARC) validation and sealing for forwarded mail.
When returned from MailFromHandler.getPipeline(), AuthPipeline
automatically:
ArcHeaderParser delivers ARC header events to the validator as
each line is captured (push-parser, no batch materialisation)ArcValidator verifies each AMS/AS instance asynchronouslyArcDmarcPolicyThe following diagram shows how data flows through the AuthPipeline at each stage, including the optional user MessageHandler for receiving teed content:
Create the pipeline in getPipeline() with a builder and register
callbacks for the checks you care about. It needs a DnsResolver
(the one for the connection's loop is
DnsResolver.forLoop(endpoint.getSelectorLoop())), the client's
address and the HELO name:
@Override
public SmtpPipeline getPipeline() {
InetAddress clientIp =
((InetSocketAddress) endpoint.getRemoteAddress()).getAddress();
DnsResolver resolver = DnsResolver.forLoop(endpoint.getSelectorLoop());
pipeline = new AuthPipeline.Builder(resolver, clientIp, heloHost)
.onSPF(new SpfCallback() {
@Override
public void spfResult(SpfResult result, String explanation) {
// invoked during MAIL FROM processing
}
})
.onDKIM(new DkimCallback() {
@Override
public void dkimResult(DkimResult result,
String signingDomain, String selector) {
// invoked at end of data
}
})
.onDMARC(new DmarcCallback() {
@Override
public void dmarcResult(DmarcResult result, DmarcPolicy policy,
String fromDomain, AuthVerdict verdict) {
// the last result: the message can now be accepted or refused
finishMessage(verdict);
}
})
.build();
return pipeline;
}
The results are asynchronous, because each check is a DNS lookup. SPF
usually completes while the message is still arriving, but DKIM and DMARC are
evaluated at the end of the data and answer a little later. A handler that
wants to refuse a message on DMARC policy therefore keeps the
MessageEndState it gets in messageComplete and
replies when the DMARC callback fires, as SmtpExample does with
state.rejectMessagePermanent(...). A result that arrives after
the transaction has been reset, or the connection closed, is discarded.
Two further options cover forwarded mail:
// Optional ARC chain validation (RFC 8617), before DKIM at end of data
builder.onARC(new ArcCallback() {
@Override
public void arcResult(ArcValidationResult result) {
// Log the chain's cv= outcome; the result is also given to DMARC
}
});
// Optional: trust a validated ARC chain for DMARC alignment (RFC 8617 §4.2)
builder.arcDmarcPolicy(new ArcDmarcPolicy() {
@Override
public ArcAuthSnapshot authSnapshot(ArcValidationResult chain,
String fromDomain, SpfResult localSpf, String localSpfDomain,
DkimResult localDkim, String localDkimDomain) {
// Return a snapshot with trusted SPF/DKIM from an earlier hop, or null
return null;
}
});
DMARC alignment compares the From domain against the SPF and DKIM domains
at the organizational domain level (relaxed mode) or exact domain
level (strict mode). Computing the organizational domain correctly requires
knowing where a public suffix ends and a registrable domain begins -
example.co.uk's organizational domain is
example.co.uk itself (since co.uk is a public
suffix, not a registrable domain), whereas example.com's is
also just example.com, but for a different reason
(com alone is the public suffix).
DmarcValidator computes this against the real
Mozilla Public Suffix List,
bundled as a classpath resource
(org/bluezoo/gumdrop/smtp/auth/public_suffix_list.dat) and
loaded by PublicSuffixList, rather than a hardcoded subset of
common TLDs - this covers every public suffix rule the list defines,
including wildcard rules (e.g. *.ck) and their exceptions
(e.g. !www.ck), and matches internationalized TLDs regardless
of whether the domain arrives in Unicode or ASCII/punycode form. Run
ant update-psl to refresh the bundled list from
publicsuffix.org.
DmarcValidator also implements the DMARC policy-and-alignment
additions from RFC 9989 ("DMARCbis"), which is largely additive and
backward-compatible - existing v=DMARC1 records continue to
work unchanged:
t= - testing mode. t=y downgrades the
enforced policy by one level (reject→quarantine,
quarantine→none) without changing the
published p=/sp=/np= values, letting
a domain owner observe what a stricter policy would do before enforcing
it.np= - policy for non-existent subdomains, used
together with psd= below.psd= - Public Suffix Domain flag. When the
Organizational Domain (see above) has no DMARC record of its own,
DmarcValidator queries one level above it; if that record
declares psd=y, its np= tag (falling back to
sp=, then p=) governs. This covers the
spec-intended case of a registry or other Public Suffix Operator
declaring policy directly above an Organizational Domain that publishes
nothing itself - it does not implement RFC 9989's full generic multi-level
DNS Tree Walk, since psd= adoption is negligible this soon
after publication and the Public Suffix List above already resolves the
Organizational Domain correctly for the overwhelming majority of
domains.
RFC 9989 §4.1 also requires v=DMARC1 to be the first tag in
a record; DmarcValidator discards any record where it is
missing or not first, matching a malformed record.
To process message headers while authentication runs in parallel, register a
MessageHandler (a MimeHandler with the RFC 5322
header events):
builder.messageHandler(new MessageHandler() {
@Override
public void header(String name, String value) throws MimeParseException {
// Receive parsed headers
}
@Override
public void addressHeader(String name, List<EmailAddress> addresses)
throws MimeParseException {
// Receive parsed address headers (From, To, Cc, etc.)
}
// ... the remaining MessageHandler and MimeHandler events
});
The handler receives events from a composite handler that also feeds the authentication checks. This avoids parsing the message twice while allowing your application to process content.
The DMARC callback receives the individual DMARC result and policy, plus a
combined AuthVerdict:
ARC preserves authentication results across intermediaries that modify
messages (mailing lists, forwarders, gateways). Each hop adds an instance
(i=1, i=2, …) comprising
ARC-Authentication-Results, ARC-Message-Signature,
and ARC-Seal. Gumdrop follows the same event-driven style as
HTTP/2 and MQTT parsers: ArcHeaderParser forwards each ARC header
to an ArcHeaderHandler while DkimMessageParser
streams the message; ArcValidator verifies signatures
asynchronously at end-of-data.
Relays that seal after local SPF/DKIM/DMARC use ArcSealer (same
signing keys and canonicalization options as DkimSigner):
ArcSealer sealer = new ArcSealer(privateKey, "example.com", "arcsel");
sealer.authservId("mx.example.com");
// Feed the same body bytes as for DKIM hashing
sealer.bodyLine(bodyBytes, 0, bodyBytes.length);
sealer.endBody();
ArcAuthenticationResults aar = new ArcAuthenticationResults();
aar.setSpf(SpfResult.PASS, "example.com");
aar.setDkim(DkimResult.PASS, "example.com");
aar.setDmarc(DmarcResult.PASS, DmarcPolicy.NONE);
List<String> newSet = sealer.seal(existingChain, messageHeaders,
incomingCv, aar);
// Prepend newSet lines (AAR, AMS, AS) before relay
RFC conformance details for ARC are listed in RFC-COMPLIANCE.md.
The DkimSigner class generates DKIM-Signature headers for outbound
messages. It supports both rsa-sha256 (RFC 6376 §3.3) and
ed25519-sha256 (RFC 8463) algorithms, with configurable header and body
canonicalization (simple or relaxed).
DkimSigner signer = new DkimSigner(privateKey, "example.com", "sel1");
signer.algorithm("rsa-sha256");
signer.headerCanonicalization("relaxed");
signer.bodyCanonicalization("relaxed");
signer.signedHeaders(Arrays.asList("from", "to", "subject", "date"));
// Feed body lines in wire format
signer.bodyLine(bodyBytes, 0, bodyBytes.length);
signer.endBody();
// Sign headers and get the DKIM-Signature header
String dkimHeader = signer.sign(rawHeaderLines);
// Prepend dkimHeader to the message before sending
Both the signer and verifier support Ed25519-SHA256 signatures. The verifier
correctly handles raw 32-byte public keys in DNS TXT records as specified by
RFC 8463 §4, converting them to Java EdECPublicKeySpec for
verification. For signing, pass an Ed25519 private key and set
the algorithm to "ed25519-sha256".
The DmarcAggregateReport class generates XML aggregate reports.
Reports can be sent to the domain owner's rua= address (now
parsed from DMARC records).
DmarcAggregateReport report = new DmarcAggregateReport();
report.setReporterOrgName("receiver.example.com");
report.setReporterEmail("dmarc-reports@receiver.example.com");
report.setReportId("report-12345");
report.setDateRange(beginEpoch, endEpoch);
// Record results for each evaluated message. The RFC 9989/9990-aware
// overload also takes np=, t=, pct, and how the record was found -
// typically straight from the DmarcValidator that produced this result.
report.addResult(sourceIP, headerFrom, policy, adkim, aspf,
dmarcResult, spfResult, spfDomain, dkimResult, dkimDomain, selector,
validator.getLastNp(), validator.getLastT(), pct,
validator.getLastDiscoveryMethod());
// Write the XML report
report.writeXML(channel); // a WritableByteChannel
The DmarcValidator parses the rua=,
ruf=, fo=, and rf= tags from DMARC
records. After evaluation, call getLastRua() /
getLastRuf() to obtain report destination URIs, and
getLastFo() to retrieve the failure reporting options.
RFC 9990 adds np, testing, and
discovery_method to policy_published, and an
optional report_metadata/generator. DmarcAggregateReport
also enforces RFC 9990's requirement that a single report cover
exactly one Policy Domain - a second, distinct headerFrom
passed to addResult throws IllegalStateException
rather than silently producing a multi-domain report; use a separate
DmarcAggregateReport instance per domain. selector
is always emitted for a reported DKIM signature (empty if unknown)
rather than omitted, per RFC 9990 making it required. pct is
retained for RFC 7489 backward compatibility even though RFC 9990 drops
it - existing report consumers may still expect it, and it costs nothing
for one that doesn't.
The DmarcForensicReport class generates per-message failure
reports in the Abuse Reporting Format (ARF, RFC 5965) with DMARC-specific
extensions (RFC 6591, RFC 9991). Reports are multipart/report
MIME messages with three parts: a human-readable description, a
machine-readable message/feedback-report, and the original
message headers.
// Check if a forensic report should be generated
String fo = validator.getLastFo();
if (DmarcForensicReport.shouldReport(fo, spfResult, dkimResult, dmarcResult)) {
DmarcForensicReport report = new DmarcForensicReport();
report.setReporterDomain("receiver.example.com");
report.setSourceIP(clientIP.getHostAddress());
report.setHeaderFrom(fromDomain);
report.setDmarcResult(dmarcResult);
report.setDmarcPolicy(policy);
report.setSpfResult(spfResult);
report.setDkimResult(dkimResult);
// Alignment, not just raw pass/fail - drives the RFC 9991
// Identity-Alignment field correctly.
report.setSpfAligned(validator.isLastSpfAligned());
report.setDkimAligned(validator.isLastDkimAligned());
report.setOriginalHeaders(messageHeaders);
report.writeMIME(channel, boundary); // a WritableByteChannel
}
The fo= tag controls when reports are generated:
0 (default) = all mechanisms fail,
1 = any mechanism fails,
d = DKIM fails,
s = SPF fails. Multiple options may be colon-separated.
RFC 9991's Identity-Alignment field lists which mechanisms
(dkim, spf) failed to authenticate an aligned
identity, or none if all did - distinct from a mechanism simply
passing, since a pass without alignment to the From domain still doesn't
satisfy DMARC. Call setSpfAligned/setDkimAligned
with the values from DmarcValidator.isLastSpfAligned() /
isLastDkimAligned() for a correct field value; without them,
it's approximated from the raw SPF/DKIM pass/fail, which is only accurate
when alignment isn't being checked separately.
Every decision is a method call on the state object for that stage. Each rejection names the condition and the server chooses the matching reply code and enhanced status code, so a handler never writes a number.
acceptSender(handler) - sender is valid (250)rejectSenderGreylist - greylisting delay (450)rejectSenderRateLimit - rate limit exceeded (450)rejectSenderStorageFull - system storage unavailable (452)rejectSenderBlockedDomain - domain on blocklist (550)rejectSenderInvalidDomain - domain does not exist (550)rejectSenderPolicy(message, handler) - business rule
violation, with your own text (553)rejectSenderSpam - known spam source (554)rejectSenderSyntax - malformed address (501)acceptRecipient(handler) - recipient is valid (250)acceptRecipientForward(forwardPath, handler) - will forward
to another host (251)rejectRecipientUnavailable - mailbox temporarily
unavailable (450)rejectRecipientSystemError - local processing error (451)rejectRecipientStorageFull - insufficient storage (452)rejectRecipientNotFound - mailbox does not exist (550)rejectRecipientNotLocal - user not handled here (551)rejectRecipientRelayDenied - relaying not permitted (551)rejectRecipientQuota - user quota full (552)rejectRecipientInvalid - mailbox name not allowed (553)rejectRecipientPolicy(message, handler) - policy violation,
with your own text (553)MessageStartState.acceptMessage(handler) to proceed to
the content, or rejectMessageStorageFull /
rejectMessageProcessingError /
rejectMessage(message, handler) (550)MessageEndState.acceptMessageDelivery(queueId, handler) to
accept the message, quoting your queue identifier in the reply, or
rejectMessageTemporary (450), rejectMessagePermanent
(550) and rejectMessagePolicy (553)
The SMTP listener performs connection-level filtering before any protocol
exchange, configured on SmtpListener:
allowedNetworks and
blockedNetworks, with pre-parsed blocks for both IPv4 and
IPv6maxConnections and
maxConnectionsPerIP prevent resource exhaustionrateLimit applies a sliding window
per IP addressmaxAuthFailures and
authLockoutTimeMsBlocked connections are rejected immediately without consuming handler resources.
Gumdrop supports the full range of SMTP AUTH mechanisms, and advertises those
the configured Realm can verify:
CRAM-MD5 and DIGEST-MD5 are not supported: they expose the exchange to offline dictionary attacks, require the server to hold the plaintext password or an equivalent, and have no channel binding (DIGEST-MD5 was moved to Historic by RFC 6331). Use SCRAM-SHA-256, or PLAIN or OAUTHBEARER over TLS.
All listed mechanisms are fully implemented on the server side, including multi-round
challenge-response exchanges (SCRAM-SHA-256) and
token-based authentication (OAUTHBEARER with JSON error challenges per
RFC 7628 §3.2.2). If a client sends * during an AUTH exchange,
the server cancels the attempt and responds with 501 (RFC 4954 §4).
Authentication integrates with Gumdrop's centralised
org.bluezoo.gumdrop.auth.Realm facility for unified credential
management across all servers. Set it with realm(...) on the
composer or the listener, and require it with authRequired(true)
(for example on a submission port). A successful AUTH reaches your handler
through HelloHandler.authenticated, where you accept or reject it.
GSSAPI additionally needs a keytab, configured on the listener:
new SmtpListener().port(587)
.configureGSSAPI(Paths.get("/etc/krb5.keytab"),
"smtp/mail.example.com@EXAMPLE.COM");
The server supports opportunistic TLS upgrade via STARTTLS (RFC 3207). When
the listener has a TlsConfig, STARTTLS is advertised in EHLO
responses. After successful TLS negotiation, the SMTP session resets and the
client must re-issue EHLO. For implicit TLS (SMTPS) use
secure(true):
new SmtpListener().port(465)
.secure(true)
.tls(TlsConfig.pem(Paths.get("cert.pem"), Paths.get("key.pem")));
The server advertises these extensions in its EHLO reply:
maxMessageSize; a larger declared or actual size is refused
with 5525.7.1RCPTMAX and MAILMAX,
when configured
Of the other commands, VRFY answers 252 without revealing
whether a mailbox exists (RFC 5321 §7.3), EXPN is refused
with 502, HELP lists the supported commands, and
ETRN (RFC 1985) is not advertised and is answered with 458
because this server does not start on-demand queue runs. The extensions with
behaviour you control are described below.
The BDAT command provides an alternative to DATA for transmitting message
content. Instead of using dot-stuffing and CRLF.CRLF termination,
BDAT specifies an exact byte count:
BDAT 1000 <exactly 1000 bytes of content> BDAT 500 LAST <exactly 500 bytes of content>
Benefits of CHUNKING:
The handler receives message content through the same messageContent()
method regardless of whether DATA or BDAT was used - the protocol difference is
handled entirely by the protocol layer.
BINARYMIME extends CHUNKING to allow raw binary content without any encoding. The sender declares binary content via the BODY parameter:
MAIL FROM:<sender@example.com> BODY=BINARYMIME
When BODY=BINARYMIME is declared, the message MUST be transmitted using BDAT because the DATA command's dot-stuffing could corrupt binary data. The server enforces this - if a client attempts to use DATA after declaring BINARYMIME, the server rejects with a 503 error.
The BODY parameter supports three values:
The handler does not need to know about BODY type - the difference is entirely a transport concern handled by the protocol layer.
Internationalized Email allows UTF-8 characters in email addresses, including the local-part, domain, and display names. When a client includes the SMTPUTF8 parameter with MAIL FROM, the server accepts addresses like:
MAIL FROM:<用户@例え.jp> SMTPUTF8 RCPT TO:<почта@пример.рф>
The smtputf8 flag is passed to the handler via the
mailFrom() callback, allowing the handler to configure message
parsing appropriately. The MessageParser class provides
setSmtputf8(boolean) for this purpose.
XCLIENT allows authorised mail proxies and content filters to pass original client connection information to the MTA. This is essential when mail passes through intermediary systems that need to preserve the original client's identity for logging, policy evaluation, and authentication checks.
Supported XCLIENT attributes:
After XCLIENT, the session resets to the greeting state and the client must re-issue EHLO. The overridden values are reflected in the connection information your handler sees for policy decisions.
XCLIENT is only available to authorised clients. Authorisation is decided
by isXclientAuthorized(InetAddress) on SmtpListener,
which returns false by default. Override it in a subclass of the
listener, and enable it only for trusted hosts:
SmtpListener listener = new SmtpListener() {
@Override
protected boolean isXclientAuthorized(InetAddress clientAddress) {
// Allow localhost and internal mail gateways
return clientAddress.isLoopbackAddress() ||
clientAddress.getHostAddress().startsWith("10.0.1.");
}
}.port(25);
XCLIENT needs an SMTP-aware proxy. An L4 relay such as an AWS Network Load
Balancer, or haproxy or nginx in TCP mode, cannot speak it, so every session
would appear to come from the relay and the address the client actually
connected to would be lost. Such a relay can instead prepend a HAProxy PROXY
protocol header (version 1 or 2) to each connection. Turn on
proxyProtocol(true) (declarative name proxy-protocol)
and enable proxy protocol v2 on the load balancer's target group:
SmtpListener listener = new SmtpListener()
.port(25);
listener.proxyProtocol(true);
The header is read before TLS (on an implicit TLS listener) and before the
session starts, so the 220 greeting is not sent until it has
arrived. The listener fails closed: a connection that does not begin with a
valid header, or does not complete one within
proxyHeaderTimeoutMs (default 5 seconds, declarative name
proxy-header-timeout), is closed. Only the first header is
consumed; anything after it is ordinary session data.
The header's source and destination become
getClientAddress() and getServerAddress() in the
connection information your handler sees, and the address literal in the
greeting uses the destination. An authorised XCLIENT still overrides them.
A v1 UNKNOWN or v2 LOCAL header, which load balancer
health checks send, is accepted and leaves the socket's own addresses. Any v2
TLVs (ALPN, authority, unique ID, TLS information, and the AWS VPC endpoint
ID) are available from Endpoint.getProxyTlvs().
Access control, rate limits, connection limits and
isXclientAuthorized always judge the real TCP peer, which is the
relay, never the address the header asserts
(Endpoint.getTransportPeerAddress()). A client that can reach a
PROXY listener directly can assert any address, so restrict the listener to
the relay's address ranges with allowedNetworks.
DSN allows senders to request notification of message delivery status. The sender can specify when to receive notifications and how much of the original message to include in the notification.
MAIL FROM parameters:
RCPT TO parameters:
Example transaction with DSN:
MAIL FROM:<sender@example.com> RET=HDRS ENVID=msg12345 RCPT TO:<user@example.org> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;user@example.org
The envelope parameters are available to the handler in
mailFrom through DeliveryRequirements:
getDsnReturn() - the RET value (FULL or
HDRS)getDsnEnvelopeId() - the ENVID value
The per-recipient parameters are available in rcptTo from
RecipientState.getRecipientDsnParameters(), which returns a
DsnRecipientParameters (or null when the command gave
none) with getNotify(), isNotifySuccess(),
isNotifyFailure(), isNotifyDelay(),
isNotifyNever(), getOrcptType() and
getOrcptAddress(). Keep them with the recipient you accept.
The MTA is responsible for generating actual DSN messages based on these parameters when delivery succeeds, fails, or is delayed.
The LIMITS extension allows the server to advertise operational limits upfront in the EHLO response. This helps clients avoid sending commands that would be rejected due to limits.
Advertised limits:
Example EHLO response with LIMITS:
250-LIMITS RCPTMAX=100 MAILMAX=50
Configuration on the composer (or on a listener, for that listener alone):
maxRecipients(int) - set RCPTMAX limitmaxTransactionsPerSession(int) - set MAILMAX limit (0 = unlimited)When limits are exceeded:
Several SMTP extensions allow senders to specify requirements for how messages
should be delivered. These are collected in the DeliveryRequirements
interface, which is passed to the handler's mailFrom() method:
Indicates that the message must only be transmitted over TLS-protected connections. If TLS cannot be guaranteed for any hop, the message should bounce.
MAIL FROM:<sender@example.com> REQUIRETLS
The server automatically supports REQUIRETLS when TLS is available. If specified
on a non-TLS connection, the server returns 530 5.7.10 REQUIRETLS requires
TLS connection.
Specifies message transfer priority from -9 (lowest) to +9 (highest), with 0 being normal priority. MTAs may use this to prioritise queue processing.
MAIL FROM:<sender@example.com> MT-PRIORITY=5
Requests that the message be held for later delivery. Two forms are supported:
MAIL FROM:<sender@example.com> HOLDFOR=3600 MAIL FROM:<sender@example.com> HOLDUNTIL=2025-12-25T00:00:00Z
HOLDFOR specifies seconds from now; HOLDUNTIL specifies
an ISO 8601 timestamp.
Specifies a delivery deadline. If the message cannot be delivered in time, it should be returned (R) or a delay DSN sent (N):
MAIL FROM:<sender@example.com> BY=86400;R MAIL FROM:<sender@example.com> BY=86400;N
All delivery requirements are available via DeliveryRequirements:
@Override
public void mailFrom(MailFromState state, EmailAddress sender,
boolean smtputf8, DeliveryRequirements delivery) {
if (delivery.isRequireTls()) {
// Must relay over TLS only
}
if (delivery.hasPriority()) {
int priority = delivery.getPriority(); // -9 to +9
}
if (delivery.isFutureRelease()) {
Instant releaseTime = delivery.getReleaseTime();
}
if (delivery.hasDeliverByDeadline()) {
Instant deadline = delivery.getDeliverByDeadline();
boolean returnOnFail = delivery.isDeliverByReturn();
}
if (delivery.hasDsnParameters()) {
DsnReturn ret = delivery.getDsnReturn();
String envid = delivery.getDsnEnvelopeId();
}
state.acceptSender(this);
}
Mail servers are configured in Java. The composer holds the settings shared
by every listener, and each SmtpListener holds its own transport
settings.
listener(SmtpListener) - add a listener; at least one is requiredsessionProvider(SmtpServerSessionProvider) - the handler
factory; required here or on a sole listenerrealm(Realm) - realm for authenticationmailboxFactory(MailboxFactory) - passed to
rcptTo for local deliverymaxMessageSize(long) - maximum message size in bytes (default: 35,882,577, about 35MB)maxRecipients(int) - maximum recipients per transaction (default: 100)maxTransactionsPerSession(int) - maximum MAIL FROM commands per session (default: 0, unlimited)authRequired(boolean) - require authentication (for a submission port)port(int) - listening port (default: 25, or 465 when secure)bindWildcard() and addresses(InetAddress...) - where to bindsecure(boolean) - implicit TLS (SMTPS)tls(TlsConfig) - certificate and key; also enables STARTTLSmaxConnections(int) and maxConnectionsPerIP(int) - connection capsrateLimit(String) - sliding-window rate limit per IPmaxAuthFailures(int) and authLockoutTimeMs(long) - brute-force protectionallowedNetworks(List<CidrNetwork>) and
blockedNetworks(List<CidrNetwork>) - CIDR allow and block listsidleTimeoutMs, readTimeoutMs, connectionTimeoutMs - timeoutsproxyProtocol(boolean) and proxyHeaderTimeoutMs(long) - require a
PROXY protocol header, and how long to wait for it (see above)maxNetInSize(int) and maxNetOutSize(int) - network buffer sizesrealm, mailboxFactory, authRequired,
maxMessageSize, maxRecipients,
maxTransactionsPerSession - per-listener overrides of the
composer's settingsconfigureGSSAPI(Path keytab, String principal) - Kerberos for AUTH GSSAPIname(String) - a name for logs and metricsAn MX listener on port 25 and a submission listener on port 587 that requires authentication, sharing one handler and realm:
TlsConfig tls = TlsConfig.pem(Paths.get("cert.pem"), Paths.get("key.pem"));
SmtpServer server = SmtpServer.compose()
.listener(new SmtpListener().name("mx").port(25).tls(tls)
.maxConnectionsPerIP(20))
.listener(new SmtpListener().name("submission").port(587).tls(tls)
.authRequired(true))
.sessionProvider(provider)
.realm(realm)
.maxMessageSize(50L * 1024 * 1024)
.server();
Gumdrop gumdrop = Gumdrop.boot();
gumdrop.addServer(server);
gumdrop.join();
Gumdrop includes a non-blocking SMTP client that shares the same event-driven architecture as the server. The client is designed for integration into MTA forward delivery components and service-to-service communication.
When an SMTP client connection is initiated from within a Gumdrop server context - such as a mail relay or gateway - it can be assigned to the same SelectorLoop as the originating server connection. This provides the same benefits described for the HTTP client:
This makes the SMTP client particularly well-suited for MTA implementations where inbound mail must be relayed to downstream servers. The relay operation executes entirely within the I/O worker without blocking.
tls(TlsConfig) configures
outbound TLS; give the TlsConfig a trustManager(...)
such as PinnedCertTrustManager for SHA-256 fingerprint pinningMailFromParams
The client is driven by a staged handler pipeline. You pass a
RemoteGreeting to SmtpClient.connect(gumdrop, handler);
each protocol stage then hands you an interface that offers only the commands
legal at that point, together with the reply handler for the answer. The flow
is greeting, EHLO (or HELO), optionally STARTTLS and AUTH, then
MAIL FROM, RCPT TO, DATA and the message body.
Gumdrop gumdrop = Gumdrop.boot();
SmtpClient client = new SmtpClient("mail.example.com", 25);
client.connect(gumdrop, new MyMailHandler());
A minimal handler that sends one message. Each reply handler implements only the outcomes it cares about plus the ones the interface requires:
public class MyMailHandler implements RemoteGreeting {
// Stage 1: the server's greeting
public void handleGreeting(ClientHelloState hello, String message, boolean esmtp) {
hello.ehlo("myhost.example.com", new EhloReplyHandler() {
public void handleEhlo(ClientSession session, boolean starttls,
long maxSize, List<String> authMethods,
boolean pipelining) {
// Stage 2: session established; start a transaction
session.mailFrom(new EmailAddress(null, "alice", "example.com", true),
new MailFromReplyHandler() {
public void handleMailFromOk(ClientEnvelope envelope) {
envelope.rcptTo(new EmailAddress(null, "bob", "example.org", true),
new RcptToReplyHandler() {
public void handleRcptToOk(ClientEnvelopeReady ready) {
ready.data(new DataReplyHandler() {
public void handleReadyForData(ClientMessageData data) {
data.writeContent(ByteBuffer.wrap(rfc5322Message)); // dot-stuffed for you
data.endMessage(new MessageReplyHandler() {
public void handleMessageAccepted(String queueId,
ClientSession session) {
session.quit();
}
public void handleTemporaryFailure(ClientSession s) {
s.quit();
}
public void handlePermanentFailure(String m,
ClientSession s) {
s.quit();
}
public void handleServiceClosing(String m) { }
});
}
public void handleTemporaryFailure(ClientEnvelopeReady e) {
e.quit();
}
public void handlePermanentFailure(String m) { }
public void handleServiceClosing(String m) { }
});
}
public void handleTemporaryFailure(ClientEnvelopeState st) {
st.quit();
}
public void handleRecipientRejected(ClientEnvelopeState st) {
st.quit();
}
public void handleServiceClosing(String m) { }
});
}
public void handleTemporaryFailure(ClientSession s) { s.quit(); }
public void handlePermanentFailure(String m) { }
public void handleServiceClosing(String m) { }
});
}
public void handleEhloNotSupported(ClientHelloState h) { h.quit(); }
public void handlePermanentFailure(String m) { }
public void handleServiceClosing(String m) { }
});
}
public void handleServiceUnavailable(String message) { }
// ClientHandler lifecycle
public void onConnected(Endpoint endpoint) { }
public void onSecurityEstablished(SecurityInfo info) { }
public void onError(Exception cause) { cause.printStackTrace(); }
public void onDisconnected() { }
}
In real code you would implement the reply handlers as named classes or a
single class with a field per stage rather than nesting them. The nesting
here shows the order of the stages. After a successful STARTTLS the client
must issue EHLO again (RFC 5321 section 4.1.1.1) and receives a fresh state
(ClientPostTls) to do so.
Message content is streamed through ClientMessageData.
Dot-stuffing is applied automatically, or BDAT (CHUNKING) is used instead of
DATA when the server advertises it:
// In handleReadyForData(ClientMessageData data):
data.writeContent(firstChunk); // may be called repeatedly
data.onWriteReady(new Runnable() { // resume when the transport can take more
public void run() {
data.writeContent(nextChunk);
data.endMessage(messageReplyHandler); // terminates the message
}
});
The SMTP server integrates with Gumdrop's OpenTelemetry implementation for distributed tracing. When telemetry is enabled, the server creates traces and spans that provide visibility into mail flow.
Session spans capture:
smtp.session_number - session index within connectionsmtp.helo or smtp.ehlo - the client's HELO/EHLO
hostname, with smtp.esmtp set for EHLOsmtp.mail_from - sender addresssmtp.rcpt_count - accepted recipientssmtp.starttls - set when STARTTLS completedsmtp.auth_mechanism and smtp.auth_user -
authentication method and username, if usedTelemetry data is exported to an OpenTelemetry Collector using the OTLP/HTTP protocol. The exporter uses Gumdrop's native HTTP client with SelectorLoop affinity for efficient, non-blocking delivery.
← Back to Main Page | HTTP Server & Client | IMAP Server | POP3 Server | NNTP Server | DNS Server | Telemetry
Gumdrop SMTP Server