An SMTP client and server library for Zig implementing RFC 5321.
0

Configure Feed

Select the types of activity you want to include in your feed.

1<!-- 2SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us> 3SPDX-License-Identifier: MIT 4--> 5 6# zsmtp 7 8An SMTP client and server library for Zig (RFC 5321). 9 10Both the client and the server run over plain `std.Io.Reader`/`std.Io.Writer` 11pairs, so they are transport-agnostic: wrap a TCP stream for real use, or 12fixed in-memory buffers in tests. Requires Zig 0.16. 13 14## Where this lives 15 16The canonical repository is on Forgejo, with mirrors on Tangled and Radicle: 17 18- <https://git.jcollie.dev/jeff/zsmtp> — issues and pull requests 19- <https://tangled.org/jcollie.dev/zsmtp> 20 21```sh 22git clone https://git.jcollie.dev/jeff/zsmtp.git 23``` 24 25On [Radicle](https://radicle.xyz/), the peer-to-peer forge, the repository is 26`rad:z3ZKHgoDKEue8FT7sV6fHZdtjxRx1`, which is the only name it has there — a 27Radicle repository is found by its ID and nothing else — so seeding or cloning 28it goes: 29 30```sh 31rad clone rad:z3ZKHgoDKEue8FT7sV6fHZdtjxRx1 32``` 33 34Cloning also seeds the repository, which helps keep it available on the 35network. 36 37The API documentation is generated from the doc comments and published at 38<https://jeff.jcollie.page/zsmtp/>; `zig build docs` builds it locally and 39`zig build docs-serve` serves it for reading. 40 41## Client 42 43```zig 44const zsmtp = @import("zsmtp"); 45 46var reply_buf: [1024]u8 = undefined; 47var client: zsmtp.Client = .init(&stream_reader.interface, &stream_writer.interface, &reply_buf); 48 49_ = try client.greet(); // read the 220 greeting 50_ = try client.hello("my-host.example.com"); // EHLO (HELO fallback), returns extensions 51try client.sendMail("me@example.com", &.{"you@example.net"}, message); 52try client.quit(); 53``` 54 55Line endings in the message are normalized to CRLF and leading dots are 56stuffed automatically. On `error.UnexpectedReply`, `client.last_reply` holds 57the server's actual code and text. `mailFrom`/`rcptTo`/`sendMessage` are also 58available individually. 59 60Addresses and the EHLO domain are checked before they are written: a value 61containing CR, LF or NUL is rejected with `error.UnsafeArgument` rather than 62sent, since it would otherwise end the command line early and let the rest of 63it be read as further SMTP commands. The check is `protocol.isSafeArgument`, 64and it is framing only — it does not claim the address is a well-formed 65mailbox. 66 67Message bodies can also be streamed instead of passed as a slice — from any 68reader via `sendMessageReader(&reader)`, or push-style via `data()`, which 69returns a writer that dot-stuffs and normalizes line endings as content 70flows through it: 71 72```zig 73var data_writer = try client.data(); 74try data_writer.interface.print("Subject: report {d}\r\n\r\n", .{id}); 75// ... stream as much as needed ... 76try data_writer.end(); // terminates the message, reads the verdict 77``` 78 79`envelope` sends MAIL FROM and every RCPT TO at once and reads all their 80replies, which against a server advertising PIPELINING 81([RFC 2920](https://datatracker.ietf.org/doc/html/rfc2920)) turns an envelope 82of *n* recipients from *n*+1 round trips into one. `hello` sets 83`client.pipelining` from the EHLO response and `envelope` falls back to 84waiting for each reply when it is false, so the result is the same either 85way: 86 87```zig 88var codes: [3]u16 = undefined; 89const accepted = try client.envelope(from, recipients, &codes, .{}); 90// codes[i] is the RCPT reply code for recipients[i]. 91``` 92 93A refused recipient is not an error — with several of them the caller is the 94one who can say whether what remains is worth sending — so compare `accepted` 95against `recipients.len`. `sendMail` makes that decision the strict way: if 96any recipient was refused it sends RSET and returns `error.UnexpectedReply` 97without delivering to the others. 98 99DATA is deliberately left out of the group, though RFC 2920 allows it as the 100last command of one. Once a server has answered DATA with 354 the transaction 101is committed, and the only ways out are to send the message or to send an 102empty one to whichever recipients were accepted; stopping the group before 103DATA keeps that choice with the caller, and costs one round trip out of the 104*n*+1 saved. 105 106`mail` and `rcpt` are the parameterized forms of `mailFrom` and `rcptTo`, 107carrying the ESMTP parameters the server advertised — today SMTPUTF8 and the 108DSN set of [RFC 3461](https://datatracker.ietf.org/doc/html/rfc3461): 109 110```zig 111try client.mail("me@example.com", .{ .ret = .hdrs, .envid = "batch 7" }); 112try client.rcpt("bob@example.net", .{ 113 .notify = .{ .on = .{ .failure = true, .delay = true } }, 114 .orcpt = .{ .addr_type = "rfc822", .address = "team@example.net" }, 115}); 116``` 117 118`ENVID` and the `ORCPT` address are xtext-encoded on the way out, so any 119bytes are safe to pass; the length limits RFC 3461 puts on the encoded form 120(100 and 500 characters) are checked and surface as 121`error.ArgumentTooLong`. Check `extensions.dsn` first — a conforming server 122answers an unrecognized parameter with 555. 123 124Setting `client.mode = .lmtp` before `hello` speaks LMTP: `LHLO` goes out in 125place of `EHLO`, and the end of a message brings back one verdict per 126accepted recipient, in the order the RCPT commands were issued. `endResults` 127is how to read them: 128 129```zig 130var data_writer = try client.data(); 131try data_writer.interface.writeAll(message); 132var verdicts = try data_writer.endResults(); 133while (try verdicts.next()) |reply| { 134 // verdicts.index counts the recipients as they are answered. 135 std.log.info("{s}: {d} {s}", .{ recipients[verdicts.index - 1], reply.code, reply.text }); 136} 137``` 138 139Every verdict must be read before the session is used again, or the next 140command is answered by a leftover reply. The simpler `end` reads them all 141and reports `error.RecipientRejected` if any was a refusal — without saying 142which, because the replies share one buffer and reading the next overwrites 143the previous. 144 145When the server advertises CHUNKING (`extensions.chunking`), `bdat` and 146`sendMessageChunked` transmit the message with length-framed BDAT chunks 147instead of DATA — verbatim, with no dot-stuffing, so text content must 148already use CRLF line endings. 149 150That framing is also what makes binary content possible. 151`mail(from, .{ .body = .binary_mime })` declares it 152([RFC 3030](https://datatracker.ietf.org/doc/html/rfc3030), needs 153`extensions.binary_mime`), after which the message may hold any octets at 154all — NULs, bare CR, a line that is nothing but a dot — and `data` refuses 155to open a DATA phase for it with `error.BinaryRequiresChunking`, which is 156the 503 the server would have sent, made one round trip earlier. RFC 3030 157is absolute that binary must not be sent to a server that did not advertise 158it, so check the capability first. 159 160### Authentication 161 162The mechanisms themselves live in 163[zig-sasl](https://git.jcollie.dev/jeff/zig-sasl), re-exported here as 164`zsmtp.sasl`, because nothing about PLAIN or CRAM-MD5 or XOAUTH2 is specific 165to SMTP — POP3 and IMAP want the same ones, and one implementation of each is 166better than three. What is specific to SMTP is `authenticate`: the `AUTH` 167command, the 334 challenges, the `*` that cancels, and the 235 that ends it. 168 169`hello` reports the server's advertised mechanism names in `extensions.auth`, 170exactly as it sent them, for `sasl.Client.selectFromList`: 171 172```zig 173var plain: zsmtp.sasl.Plain = .init("user", "password"); 174var cram: zsmtp.sasl.CramMd5 = .init("user", "password"); 175 176const extensions = try client.hello("my-host.example.com"); 177const mechanism = zsmtp.sasl.Client.selectFromList( 178 &.{ plain.client(), cram.client() }, // in order of preference 179 extensions.auth, 180 client.security == .encrypted, 181) orelse return error.NoSupportedMechanism; 182try client.authenticate(mechanism); 183``` 184 185A 535 rejection surfaces as `error.AuthenticationFailed` with the reply in 186`last_reply`. 187 188PLAIN, LOGIN and the OAuth mechanisms put a credential on the wire that an 189eavesdropper could reuse — base64 is not encryption, and a bearer token is 190worth more than a password because it authorizes elsewhere too. The client 191refuses those unless `client.security` is `.encrypted`, returning 192`error.InsecureTransport` before anything is sent, and `selectFromList` 193skips them for the same reason: on a plaintext session the preference order 194above falls through PLAIN to CRAM-MD5, which sends a proof rather than the 195secret. 196 197The library is handed a reader and a writer and cannot see what is underneath 198them, so it assumes the worst: `setTransport` records the answer for a 199STARTTLS upgrade, and a session speaking TLS from the first byte sets 200`client.security = .encrypted` itself. For a connection protected by 201something the library cannot see — a unix socket, an SSH tunnel, a loopback 202test — `client.allow_cleartext_auth = true` permits them without claiming the 203transport is encrypted. 204 205One error is worth knowing about even if it never fires for PLAIN: 206`error.ServerNotAuthenticated` means the server reported success while the 207mechanism had not finished proving what it set out to prove. For a one-way 208mechanism that cannot happen. For SCRAM (via 209[zig-scram](https://git.jcollie.dev/jeff/zig-scram)'s `scram-sasl` module) it 210means the server never produced its own signature — which is what something 211in the middle, holding no verifier, would do. 212 213### TLS 214 215`zsmtp.Tls` wraps [ianic/tls.zig](https://github.com/ianic/tls.zig) and 216verifies against the system trust store by default (a caller-managed CA 217bundle and an insecure mode are also available). The stream reader/writer 218handed to it need buffers of at least `zsmtp.Tls.min_buffer_len` bytes, and 219`init` must run at the value's final address (the connection holds interior 220pointers). The standard library's TLS client is deliberately not used: it 221requires the optional TLS 1.3 middlebox-compatibility ChangeCipherSpec 222record, which servers like Exim disable. 223 224Implicit TLS (port 465) — handshake first, then speak SMTP: 225 226```zig 227var tls: zsmtp.Tls = undefined; 228try tls.init(io, gpa, &stream_reader.interface, &stream_writer.interface, .{ 229 .host = "smtp.example.com", 230}); 231defer tls.deinit(gpa); 232var client: zsmtp.Client = .init(tls.reader(), tls.writer(), &reply_buf); 233client.security = .encrypted; // the transport is TLS; `init` cannot tell 234// ... greet, hello, sendMail ... 235try client.quit(); 236try tls.end(); // close_notify, before closing the socket 237``` 238 239STARTTLS (port 587) — upgrade mid-session, then EHLO again: 240 241```zig 242_ = try client.greet(); 243_ = try client.hello("my-host.example.com"); // check .starttls in the result 244try client.starttls(); 245var tls: zsmtp.Tls = undefined; 246try tls.init(io, gpa, &stream_reader.interface, &stream_writer.interface, .{ 247 .host = "smtp.example.com", 248}); 249client.setTransport(tls.reader(), tls.writer(), .encrypted); 250_ = try client.hello("my-host.example.com"); // server state was reset 251``` 252 253## Server 254 255```zig 256var session: zsmtp.Server = .init(&stream_reader.interface, &stream_writer.interface, .{ 257 .context = &my_state, 258 .vtable = &.{ 259 .authenticate = onAuth, // optional; enables AUTH PLAIN and LOGIN 260 .rcptTo = onRcptTo, // optional; accept/reject each Recipient 261 .message = onMessage, // required; receives envelope + message data 262 }, 263}, .{ .hostname = "mx.example.com" }); 264try session.run(gpa); 265``` 266 267With an `authenticate` callback the session advertises and accepts AUTH 268PLAIN and AUTH LOGIN (RFC 4954); setting `Options.require_auth` rejects MAIL 269with 530 until the client has authenticated. 270 271Instead of `message` (which collects the whole body in memory, bounded by 272`max_message_size`), a handler can set `messageReader` to stream it: the 273callback receives an `Io.Reader` yielding the unstuffed message content, 274and anything left unread is drained by the session. 275 276`run` serves one connection until QUIT or disconnect, enforcing command 277sequencing, recipient and message-size limits, and un-stuffing message data. 278Messages may also arrive via BDAT chunks (CHUNKING is advertised); both 279the collecting and streaming handler paths receive the reassembled content. 280MAIL parameters are validated: `SIZE=` (RFC 1870) is rejected early with 552 281when it exceeds `max_message_size`, `BODY=7BIT`/`BODY=8BITMIME` (RFC 6152) 282are accepted, and unrecognized parameters get 555; the declared size and 283body type reach the handler via `Envelope`. Listening, accepting, and 284concurrency are up to the caller. 285 286The server holds back the replies that RFC 2920 §3.2 permits — RSET, MAIL 287FROM and RCPT TO — so that a pipelined group is answered in one write, and 288sends everything pending the moment its input is empty. The condition is what 289makes that safe rather than a deadlock: a reply is only ever held while there 290is another command already waiting to be answered. 291 292Setting `Options.protocol = .lmtp` makes the session speak LMTP 293([RFC 2033](https://datatracker.ietf.org/doc/html/rfc2033)) instead: `LHLO` 294greets and `HELO`/`EHLO` are refused with 500, and the end of a message 295draws one reply per accepted recipient rather than one for the message — 296including a second reply for a recipient named twice. The `recipientResult` 297callback supplies each verdict: 298 299```zig 300fn onRecipientResult(ctx: ?*anyopaque, envelope: zsmtp.Server.Envelope, index: usize) zsmtp.Server.Decision { 301 return if (mailboxIsFull(envelope.recipients[index].address)) 302 .{ .reject = .{ .code = 452, .text = "4.2.2 Mailbox full" } } 303 else 304 .accept; 305} 306``` 307 308Without it every recipient is told the same thing, which is correct but 309gains nothing over SMTP. A message the handler rejected outright is reported 310as that rejection for each recipient, since it failed for all of them. LMTP 311is meant for the hop between a queueing MTA and whatever writes to mailboxes; 312RFC 2033 §5 forbids it on TCP port 25 and advises against wide-area use. 313 314BINARYMIME ([RFC 3030](https://datatracker.ietf.org/doc/html/rfc3030)) is 315advertised alongside CHUNKING, which the RFC requires of anything offering 316it. `BODY=BINARYMIME` arrives as `Envelope.body`, DATA for such a message is 317refused with 503, and the content reaches the handler exactly as it was 318sent — the BDAT path copies octets and has no line structure to normalize. 319 320DSN ([RFC 3461](https://datatracker.ietf.org/doc/html/rfc3461)) is 321advertised. `RET=` and `ENVID=` on MAIL arrive as `Envelope.ret` and 322`Envelope.envid`, and `NOTIFY=` and `ORCPT=` on RCPT arrive as 323`Recipient.notify` and `Recipient.orcpt` — at the `rcptTo` callback, which 324receives the whole `Recipient`, and again on the `Envelope` afterwards. The 325xtext values are decoded, the length limits enforced, and a malformed value 326answered with 501. Like everything else handed to a callback, those slices 327live only for the duration of the call; keep what you need by copying it. 328 329To advertise and accept STARTTLS (TLS 1.3, via 330[ianic/tls.zig](https://github.com/ianic/tls.zig)), pass a certificate key 331pair; the stream buffers must then be at least `zsmtp.tls.input_buffer_len` / 332`zsmtp.tls.output_buffer_len` bytes, since the handshake runs over them: 333 334```zig 335var auth: zsmtp.tls.config.CertKeyPair = 336 try .fromFilePath(gpa, io, .cwd(), "cert.pem", "key.pem"); 337defer auth.deinit(gpa); 338 339var session: zsmtp.Server = .init(&stream_reader.interface, &stream_writer.interface, handler, .{ 340 .hostname = "mx.example.com", 341 .tls = .{ .io = io, .auth = &auth }, 342}); 343try session.run(gpa); 344``` 345 346On STARTTLS the session answers 220, performs the server handshake, swaps 347its transport to the encrypted connection, and resets state per RFC 3207 (the 348client must EHLO again). With `.mode = .implicit` the handshake instead runs 349before the greeting (SMTPS, port 465 style): 350 351```zig 352var session: zsmtp.Server = .init(&stream_reader.interface, &stream_writer.interface, handler, .{ 353 .hostname = "mx.example.com", 354 .tls = .{ .io = io, .auth = &auth, .mode = .implicit }, 355}); 356``` 357 358## Demo CLI 359 360```sh 361zig build 362 363# Debug server that prints received messages to stdout 364# (with a cert/key pair it advertises and accepts STARTTLS): 365./zig-out/bin/zsmtp serve 2525 366./zig-out/bin/zsmtp serve --tls-cert cert.pem --tls-key key.pem 2525 367./zig-out/bin/zsmtp serve --tls-cert cert.pem --tls-key key.pem --implicit-tls 2465 368 369# Send a message read from stdin: 370printf 'Subject: hi\r\n\r\nhello\r\n' | \ 371 ./zig-out/bin/zsmtp send 127.0.0.1 2525 me@example.com you@example.net 372 373# Same, over implicit TLS or STARTTLS (--insecure skips cert verification): 374zsmtp send --tls smtp.example.com 465 me@example.com you@example.net 375zsmtp send --starttls smtp.example.com 587 me@example.com you@example.net 376 377# Send arbitrary binary content (RFC 3030), framed by BDAT rather than DATA: 378./zig-out/bin/zsmtp send --binarymime 127.0.0.1 2525 me@example.com you@example.net \ 379 < some-binary-file 380 381# Speak LMTP (RFC 2033) instead of SMTP. The server reports one verdict per 382# recipient, and --fail-delivery makes one of them fail to show it: 383./zig-out/bin/zsmtp serve --lmtp --fail-delivery bad@example.net 2529 384printf 'Subject: hi\r\n\r\nhello\r\n' | \ 385 ./zig-out/bin/zsmtp send --lmtp 127.0.0.1 2529 me@example.com \ 386 good@example.net bad@example.net 387 388# Request a delivery status notification (RFC 3461): 389zsmtp send --ret hdrs --envid 'batch 7' --notify success,failure \ 390 --orcpt team@example.net 127.0.0.1 2525 me@example.com you@example.net 391 392# Authenticate. Over a plaintext connection this refuses PLAIN and LOGIN 393# rather than put the password on the wire; --allow-cleartext-auth overrides 394# that for a connection protected by other means: 395zsmtp send --starttls --user me --password secret smtp.example.com 587 \ 396 me@example.com you@example.net 397``` 398 399## Status 400 401TLS is supported on both sides via 402[ianic/tls.zig](https://github.com/ianic/tls.zig): the client does implicit 403TLS and STARTTLS via `zsmtp.Tls`, and the server accepts both STARTTLS and 404implicit TLS (TLS 1.3 only). AUTH covers PLAIN, LOGIN, and CRAM-MD5 on the 405client and PLAIN and LOGIN on the server. Message bodies can be streamed on 406both sides, and the server validates MAIL and RCPT parameters (SIZE=, BODY=, 407and the DSN set RET=, ENVID=, NOTIFY=, ORCPT=). Both sides also speak LMTP, 408where a message ends with one verdict per recipient rather than one for the 409message, and both use PIPELINING, which collapses an envelope into a single 410round trip. 411 412## Known gaps 413 414Measured against the implementations people are likely to be coming from — 415Postfix, Exim and Haraka on the server side, Go's `net/smtp`, Python's 416`smtplib`, lettre and Nodemailer on the client side. Kept here so the list 417is one thing rather than a rediscovery each time. 418 419### Out of scope, not missing 420 421- **Message composition.** No MIME builder, headers, attachments, transfer 422 encodings, `Message-ID` or `Date` generation. zsmtp carries a message that 423 already exists; building one is RFC 5322's job and belongs in a library of 424 its own. 425- **DSN report generation** 426 ([RFC 3464](https://datatracker.ietf.org/doc/html/rfc3464)). The SMTP half 427 of DSN — RFC 3461's `RET`, `ENVID`, `NOTIFY` and `ORCPT` — is implemented 428 on both sides, but nothing here builds the `multipart/report` message that 429 carries a delivery status back to the sender. That is message composition 430 by another name, so it goes with the library above. 431- **Everything an MTA does around a session.** No queue, no retry schedule, 432 no MX resolution, no routing, no mailbox store. "Server" here means a 433 session handler: listening, accepting and concurrency are the caller's. 434 435### Protocol 436 437- **`AUTH=` on MAIL FROM** ([RFC 4954 §5](https://datatracker.ietf.org/doc/html/rfc4954#section-5)), 438 which a trusted relay uses to forward the identity that originally 439 authenticated. The client-side *mechanisms* are no longer a gap — PLAIN, 440 LOGIN, CRAM-MD5, EXTERNAL, XOAUTH2, OAUTHBEARER and SCRAM all come from 441 zig-sasl — but the **server** still understands only PLAIN and LOGIN, and 442 only against a plaintext password. 443- **Client certificates** — neither side can present or verify one. 444- **No enhanced status code accessor** — the server emits `x.y.z` on every 445 reply, but `Reply` exposes only `code` and the raw text. 446- `EXPN` is unrecognized rather than unimplemented, so it answers 500 where 447 [RFC 5321 §4.2.4](https://datatracker.ietf.org/doc/html/rfc5321#section-4.2.4) 448 wants 502. 449- Niche and absent: REQUIRETLS, MT-PRIORITY, DELIVERBY, FUTURERELEASE, ETRN. 450 451### Server 452 453- **No `Received:` header.** 454 [RFC 5321 §4.4](https://datatracker.ietf.org/doc/html/rfc5321#section-4.4) 455 requires a receiving server to stamp one. 456- **The handler never sees the connection** — no connect callback, no peer 457 address, no TLS state. Greylisting, DNSBLs, SPF and per-IP policy cannot 458 be built on top, and a `Received:` header cannot be written without it. 459- **No timeouts**, so a client that connects and says nothing holds the 460 session forever; 461 [RFC 5321 §4.5.3.2](https://datatracker.ietf.org/doc/html/rfc5321#section-4.5.3.2) 462 specifies per-command limits. 463- **No abuse limits** beyond `max_recipients`: unlimited failed AUTH 464 attempts, no error-count disconnect, no command budget. 465- **No `require_tls`** to go with `require_auth`. 466- **No PROXY protocol, XCLIENT or XFORWARD**, so the real peer address is 467 lost behind a load balancer. 468- No filter or milter hook, and so no DKIM, SPF, DMARC or ARC. 469- No logging or tracing hooks. 470- `max_message_size` is not enforced in `messageReader` mode. 471 472### Client 473 474- **`sendMail` is all-or-nothing on recipients** — a refused RCPT abandons 475 the transaction, where `smtplib.sendmail` delivers to the rest and reports 476 the refusals. `envelope` gives a caller the per-recipient codes to decide 477 for itself, but no higher-level call does that decision for it. 478- **No `SIZE=` on MAIL**, though the client parses the capability off EHLO: 479 `max_size` is read and never used, so nothing checks that a message fits 480 before transmitting it. 481- No MX resolution or connect helper, no 4xx retry or backoff, no connection 482 reuse helper. 483 484## Standards 485 486- [RFC 5321](https://datatracker.ietf.org/doc/html/rfc5321) — Simple Mail 487 Transfer Protocol: the command/reply protocol, multiline replies, 488 dot-stuffing, reply classes, and ESMTP parameter syntax (client and 489 server). 490- [RFC 1870](https://datatracker.ietf.org/doc/html/rfc1870) — SIZE: 491 advertised and enforced by the server (oversize declarations are rejected 492 with 552 before DATA); parsed from EHLO by the client. 493- [RFC 6152](https://datatracker.ietf.org/doc/html/rfc6152) — 8BITMIME: 494 advertised by the server and `BODY=` validated; parsed by the client. 495- [RFC 3030](https://datatracker.ietf.org/doc/html/rfc3030) — CHUNKING 496 (BDAT) and BINARYMIME: client and server, with length-based framing and no 497 dot-stuffing. `BODY=BINARYMIME` is advertised, accepted and delivered bit 498 for bit, and DATA is refused with 503 for a message that declared it, 499 since binary content cannot be framed by a line holding a single dot. 500- [RFC 3461](https://datatracker.ietf.org/doc/html/rfc3461) — DSN: 501 advertised by the server, which parses and validates `RET=`/`ENVID=` on 502 MAIL and `NOTIFY=`/`ORCPT=` on RCPT and hands them to the handler; the 503 client sends them through `mail`/`rcpt`. Includes the xtext codec of §4. 504 Generating the report message itself (RFC 3464) is out of scope. 505- [RFC 2033](https://datatracker.ietf.org/doc/html/rfc2033) — LMTP: client 506 and server, via `Client.mode` and `Server.Options.protocol`. `LHLO` 507 replaces `EHLO` and the end of a message draws one reply per accepted 508 recipient instead of one for the message, after DATA and after `BDAT 509 LAST` alike. 510- [RFC 2920](https://datatracker.ietf.org/doc/html/rfc2920) — PIPELINING: 511 the client sends a whole envelope as one group through `envelope`, and the 512 server holds back the replies it is allowed to (RSET, MAIL, RCPT) so they 513 leave together, sending everything pending the moment its input runs dry. 514- [RFC 3207](https://datatracker.ietf.org/doc/html/rfc3207) — STARTTLS: 515 client and server, including the mandatory post-handshake state reset. 516- [RFC 8314](https://datatracker.ietf.org/doc/html/rfc8314) — implicit TLS 517 (SMTPS): client (`Tls` before any SMTP traffic) and server 518 (`.mode = .implicit`). 519- [RFC 4954](https://datatracker.ietf.org/doc/html/rfc4954) — AUTH: client 520 and server, including initial responses, empty challenges and `*` 521 cancellation. The client drives any mechanism from 522 [zig-sasl](https://git.jcollie.dev/jeff/zig-sasl); the server still 523 implements PLAIN ([RFC 4616](https://datatracker.ietf.org/doc/html/rfc4616)) 524 and the de-facto 525 [LOGIN](https://datatracker.ietf.org/doc/html/draft-murchison-sasl-login-00) 526 itself, because zig-sasl's server side does not yet reach past PLAIN. 527- [RFC 3463](https://datatracker.ietf.org/doc/html/rfc3463) / 528 [RFC 2034](https://datatracker.ietf.org/doc/html/rfc2034) — enhanced 529 status codes: carried in every server reply and advertised via 530 ENHANCEDSTATUSCODES; detected by the client. 531- [RFC 6531](https://datatracker.ietf.org/doc/html/rfc6531) — SMTPUTF8: 532 client (`mailFromUtf8`) and server (advertised; non-ASCII addresses 533 require the parameter and must be valid UTF-8, rejected with 553 5.6.7 534 per [RFC 6533](https://datatracker.ietf.org/doc/html/rfc6533) otherwise; 535 the flag reaches handlers via `Envelope.smtputf8`). 536 537TLS itself (TLS 1.3, [RFC 8446](https://datatracker.ietf.org/doc/html/rfc8446)) 538is provided by [ianic/tls.zig](https://github.com/ianic/tls.zig). 539 540## References cited 541 542The specifications this implementation was written against, and the outside 543work it borrows from, in the RFC citation format so that a reference here 544matches one anywhere else. The **Standards** section above says what is 545implemented of each; this one says what each document *is*. Every entry is 546also filed in the project bibliography, so a citation can be taken from there 547rather than composed; the RFCs are keyed by their DOIs (`10.17487/RFC5321` 548and so on). 549 550- **[RFC1870]** Klensin, J., Freed, N., and K. Moore, "SMTP Service 551 Extension for Message Size Declaration", RFC 1870, November 1995, 552 <https://www.rfc-editor.org/info/rfc1870>. 553- **[RFC2033]** Myers, J., "Local Mail Transfer Protocol", RFC 2033, 554 October 1996, <https://www.rfc-editor.org/info/rfc2033>. 555- **[RFC2034]** Freed, N., "SMTP Service Extension for Returning Enhanced 556 Error Codes", RFC 2034, October 1996, 557 <https://www.rfc-editor.org/info/rfc2034>. 558- **[RFC2195]** Klensin, J., Catoe, R., and P. Krumviede, "IMAP/POP 559 AUTHorize Extension for Simple Challenge/Response", RFC 2195, 560 September 1997, <https://www.rfc-editor.org/info/rfc2195>. 561- **[RFC2920]** Freed, N., "SMTP Service Extension for Command Pipelining", 562 RFC 2920, September 2000, <https://www.rfc-editor.org/info/rfc2920>. 563- **[RFC3030]** Vaudreuil, G., "SMTP Service Extensions for Transmission of 564 Large and Binary MIME Messages", RFC 3030, December 2000, 565 <https://www.rfc-editor.org/info/rfc3030>. 566- **[RFC3207]** Hoffman, P., "SMTP Service Extension for Secure SMTP over 567 Transport Layer Security", RFC 3207, February 2002, 568 <https://www.rfc-editor.org/info/rfc3207>. 569- **[RFC3461]** Moore, K., "Simple Mail Transfer Protocol (SMTP) Service 570 Extension for Delivery Status Notifications (DSNs)", RFC 3461, 571 January 2003, <https://www.rfc-editor.org/info/rfc3461>. 572- **[RFC3463]** Vaudreuil, G., "Enhanced Mail System Status Codes", 573 RFC 3463, January 2003, <https://www.rfc-editor.org/info/rfc3463>. 574- **[RFC3464]** Moore, K. and G. Vaudreuil, "An Extensible Message Format 575 for Delivery Status Notifications", RFC 3464, January 2003, 576 <https://www.rfc-editor.org/info/rfc3464>. *(Cited as out of scope: the 577 report message itself.)* 578- **[RFC4616]** Zeilenga, K., "The PLAIN Simple Authentication and Security 579 Layer (SASL) Mechanism", RFC 4616, August 2006, 580 <https://www.rfc-editor.org/info/rfc4616>. 581- **[RFC4954]** Siemborski, R. and A. Melnikov, "SMTP Service Extension for 582 Authentication", RFC 4954, July 2007, 583 <https://www.rfc-editor.org/info/rfc4954>. 584- **[RFC5321]** Klensin, J., "Simple Mail Transfer Protocol", RFC 5321, 585 October 2008, <https://www.rfc-editor.org/info/rfc5321>. 586- **[RFC5322]** Resnick, P., Ed., "Internet Message Format", RFC 5322, 587 October 2008, <https://www.rfc-editor.org/info/rfc5322>. *(Cited as out 588 of scope: the format of the message this library carries.)* 589- **[RFC6152]** Klensin, J., Freed, N., Rose, M., and D. Crocker, "SMTP 590 Service Extension for 8-bit MIME Transport", RFC 6152, March 2011, 591 <https://www.rfc-editor.org/info/rfc6152>. 592- **[RFC6531]** Yao, J. and W. Mao, "SMTP Extension for Internationalized 593 Email", RFC 6531, February 2012, 594 <https://www.rfc-editor.org/info/rfc6531>. 595- **[RFC6533]** Hansen, T., Ed., Newman, C., and A. Melnikov, 596 "Internationalized Delivery Status and Disposition Notifications", 597 RFC 6533, February 2012, <https://www.rfc-editor.org/info/rfc6533>. 598- **[RFC7628]** Mills, W., Showalter, T., and H. Tschofenig, "A Set of 599 Simple Authentication and Security Layer (SASL) Mechanisms for OAuth", 600 RFC 7628, August 2015, <https://www.rfc-editor.org/info/rfc7628>. 601 *(Cited as a gap.)* 602- **[RFC7677]** Hansen, T., "SCRAM-SHA-256 and SCRAM-SHA-256-PLUS Simple 603 Authentication and Security Layer (SASL) Mechanisms", RFC 7677, 604 November 2015, <https://www.rfc-editor.org/info/rfc7677>. *(Cited as a 605 gap.)* 606- **[RFC8314]** Moore, K. and C. Newman, "Cleartext Considered Obsolete: 607 Use of Transport Layer Security (TLS) for Email Submission and Access", 608 RFC 8314, January 2018, <https://www.rfc-editor.org/info/rfc8314>. 609- **[RFC8446]** Rescorla, E., "The Transport Layer Security (TLS) Protocol 610 Version 1.3", RFC 8446, August 2018, 611 <https://www.rfc-editor.org/info/rfc8446>. 612- **[SASL-LOGIN]** Murchison, K. and M. Crispin, "The LOGIN SASL 613 Mechanism", Work in Progress, Internet-Draft, 614 draft-murchison-sasl-login-00, August 2003, 615 <https://datatracker.ietf.org/doc/html/draft-murchison-sasl-login-00>. 616 The draft expired and LOGIN was never standardized; it is implemented 617 here because servers still ask for it. 618- **[TLS.ZIG]** Ianic, "tls.zig — TLS 1.2/1.3 implementation in Zig", 619 <https://github.com/ianic/tls.zig>. Provides the TLS on both sides; see 620 the **TLS** section for why the standard library's client is not used. 621- **[ISEMAIL]** Sayers, D., "is_email — an email address validator and its 622 test suite", BSD-3-Clause, <https://github.com/dominicsayers/isemail>. 623 The address corpus the path parser is checked against; see **Tests**. 624- **[EXIM]** The Exim Maintainers, "Exim Internet Mailer", 625 GPL-2.0-or-later, <https://www.exim.org/>. The protocol torture script 626 and the gauntlet unit test's dialogue are adapted from its test suite. 627 628## Tests 629 630```sh 631zig build test 632zig build test --fuzz # run the fuzz tests under the fuzzer (endless) 633``` 634 635The fuzz tests cover parser crash-safety (`Command.parse`, `Reply.read`), 636whole-session robustness against arbitrary bytes on both the client and 637server side, and two differential properties: the streaming `DataWriter` 638must produce byte-identical output to the slice-based `writeStuffed` under 639fuzzer-chosen chunk boundaries, and the collecting and streaming server 640DATA paths must yield identical message content. 641 642### Protocol torture testing with exim's test client 643 644Exim's scriptable SMTP test client (`test/src/client.c` in the exim 645source) sends raw protocol lines and asserts reply prefixes. The exim 646source is declared as a *lazy* Zig dependency, fetched only on demand: 647 648```sh 649zig build -Dexim-client # fetches exim, installs zig-out/bin/exim-client 650./zig-out/bin/zsmtp serve 2525 & 651./zig-out/bin/exim-client 127.0.0.1 2525 < test/protocol-torture.script 652``` 653 654### Address corpus testing with the is_email suite 655 656Dominic Sayers' [is_email](https://github.com/dominicsayers/isemail) test 657suite (BSD-3-Clause) is declared as a *lazy* Zig dependency; nothing from 658it is copied into this repository. On demand, the corpus test embeds its 659XML test files, extracts the 125 addresses valid at the RFC 5321 layer, 660and checks that each passes through the path parser byte-for-byte: 661 662```sh 663zig build test -Disemail-corpus # fetches the suite and runs the corpus test 664``` 665 666Without the option the corpus test is skipped. 667 668`test/protocol-torture.script` is a 28-reply dialogue distilled from 669exim's own test suite (syntax errors, sequencing violations, parameter 670validation, dot-stuffing); the same dialogue is asserted byte-for-byte 671as a unit test in `Server.zig`. 672 673The library is MIT-licensed; the small amount of test-only material adapted 674from exim's test suite (the torture script and the gauntlet unit test's 675dialogue) is GPL-2.0-or-later, marked with SPDX snippet tags and REUSE.toml 676annotations. 677 678Note: Zig 0.16.0's fuzz *driver* is broken out of the box (its bundled 679test runner fails to compile in fuzz mode, and the coverage server panics 680on a test binary with no fuzz tests); both are fixed on Zig master. Until 681then, fuzzing needs a patched copy of the standard library via 682`zig build --zig-lib-dir <patched-lib> test --fuzz`. The fuzz tests 683themselves also run once per invocation as part of the normal 684`zig build test` suite. 685 686Interoperability against third-party implementations is covered by a NixOS 687VM test (`nix/interop-test.nix`): the zsmtp client delivers mail to Postfix 688and Exim over plaintext, STARTTLS, and implicit TLS against each, and swaks 689delivers to the zsmtp server over plaintext and STARTTLS. 690 691```sh 692nix build .#zsmtp # build the package 693nix build .#checks.x86_64-linux.interop # run the VM interop test 694```