An SMTP client and server library for Zig implementing RFC 5321.
1// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>
2// SPDX-License-Identifier: MIT
3
4//! Demo CLI for the zsmtp library.
5//!
6//! zsmtp send [--tls|--starttls] [--insecure] [--allow-cleartext-auth]
7//! [--chunking] [--smtputf8] [--user <u> --password <p>]
8//! [--auth-method plain|login|cram-md5]
9//! [--ret full|hdrs] [--envid <id>]
10//! [--notify never|success,failure,delay] [--orcpt <address>]
11//! [--lmtp] [--binarymime] <host> <port> <from> <to>...
12//! send a message read from stdin; --tls speaks TLS from the first
13//! byte (port 465 style), --starttls upgrades after EHLO (port 587
14//! style), --insecure skips certificate verification, --user/--password
15//! authenticate with the best advertised mechanism (or the one forced
16//! by --auth-method), and --allow-cleartext-auth permits a mechanism
17//! that sends the password over an unencrypted connection; the DSN
18//! options (RFC 3461) are --ret and --envid on the message and
19//! --notify and --orcpt on every recipient; --binarymime sends the
20//! input as BODY=BINARYMIME over BDAT, byte for byte
21//! zsmtp serve [--tls-cert <pem> --tls-key <pem> [--implicit-tls]]
22//! [--auth <user>:<pass>] [--lmtp [--fail-delivery <address>]]
23//! <port>
24//! run a debug server on 127.0.0.1 that prints received messages;
25//! --auth requires authentication with the given credentials; with a
26//! certificate and key it advertises and accepts STARTTLS, or speaks
27//! TLS from the first byte with --implicit-tls; --lmtp speaks LMTP
28//! instead of SMTP, where --fail-delivery names one recipient to
29//! report as undeliverable at the end of the message
30
31const std = @import("std");
32const Io = std.Io;
33const zsmtp = @import("zsmtp");
34
35pub fn main(init: std.process.Init) !void {
36 const arena = init.arena.allocator();
37 const io = init.io;
38 const args = try init.minimal.args.toSlice(arena);
39
40 if (args.len >= 2 and std.mem.eql(u8, args[1], "send")) {
41 var config: SendConfig = .{};
42 var rest = args[2..];
43 while (rest.len > 0 and std.mem.startsWith(u8, rest[0], "--")) {
44 if (std.mem.eql(u8, rest[0], "--tls")) {
45 config.mode = .tls;
46 } else if (std.mem.eql(u8, rest[0], "--starttls")) {
47 config.mode = .starttls;
48 } else if (std.mem.eql(u8, rest[0], "--insecure")) {
49 config.insecure = true;
50 } else if (std.mem.eql(u8, rest[0], "--allow-cleartext-auth")) {
51 config.allow_cleartext_auth = true;
52 } else if (std.mem.eql(u8, rest[0], "--chunking")) {
53 config.chunking = true;
54 } else if (std.mem.eql(u8, rest[0], "--smtputf8")) {
55 config.smtputf8 = true;
56 } else if (std.mem.eql(u8, rest[0], "--lmtp")) {
57 config.protocol = .lmtp;
58 } else if (std.mem.eql(u8, rest[0], "--binarymime")) {
59 // Binary content can only be framed by BDAT, so this is
60 // chunking plus a declaration of what the chunks hold.
61 config.body = .binary_mime;
62 config.chunking = true;
63 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--ret")) {
64 config.ret = zsmtp.protocol.Ret.parse(rest[1]) catch return usage();
65 rest = rest[1..];
66 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--envid")) {
67 config.envid = rest[1];
68 rest = rest[1..];
69 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--notify")) {
70 config.notify = zsmtp.protocol.Notify.parse(rest[1]) catch return usage();
71 rest = rest[1..];
72 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--orcpt")) {
73 // Applied to every recipient, which is all a one-shot
74 // sender can sensibly do with it.
75 config.orcpt = rest[1];
76 rest = rest[1..];
77 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--user")) {
78 config.username = rest[1];
79 rest = rest[1..];
80 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--password")) {
81 config.password = rest[1];
82 rest = rest[1..];
83 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--auth-method")) {
84 config.auth_method = std.meta.stringToEnum(
85 @TypeOf(config.auth_method),
86 rest[1],
87 ) orelse if (std.mem.eql(u8, rest[1], "cram-md5")) .cram_md5 else return usage();
88 rest = rest[1..];
89 } else {
90 return usage();
91 }
92 rest = rest[1..];
93 }
94 if ((config.username == null) != (config.password == null)) return usage();
95 if (rest.len < 4) return usage();
96 return send(io, arena, config, rest[0], rest[1], rest[2], rest[3..]);
97 }
98 if (args.len >= 2 and std.mem.eql(u8, args[1], "serve")) {
99 var config: ServeConfig = .{};
100 var rest = args[2..];
101 while (rest.len > 0 and std.mem.startsWith(u8, rest[0], "--")) {
102 if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--tls-cert")) {
103 config.cert_path = rest[1];
104 rest = rest[1..];
105 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--tls-key")) {
106 config.key_path = rest[1];
107 rest = rest[1..];
108 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--auth")) {
109 const sep = std.mem.indexOfScalar(u8, rest[1], ':') orelse return usage();
110 config.username = rest[1][0..sep];
111 config.password = rest[1][sep + 1 ..];
112 rest = rest[1..];
113 } else if (std.mem.eql(u8, rest[0], "--implicit-tls")) {
114 config.implicit_tls = true;
115 } else if (std.mem.eql(u8, rest[0], "--lmtp")) {
116 config.protocol = .lmtp;
117 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--fail-delivery")) {
118 config.fail_delivery = rest[1];
119 rest = rest[1..];
120 } else {
121 return usage();
122 }
123 rest = rest[1..];
124 }
125 if (rest.len != 1) return usage();
126 if ((config.cert_path == null) != (config.key_path == null)) return usage();
127 if (config.implicit_tls and config.cert_path == null) return usage();
128 if (config.fail_delivery != null and config.protocol != .lmtp) return usage();
129 return serve(io, arena, config, rest[0]);
130 }
131 return usage();
132}
133
134const ServeConfig = struct {
135 cert_path: ?[]const u8 = null,
136 key_path: ?[]const u8 = null,
137 implicit_tls: bool = false,
138 protocol: zsmtp.Server.Protocol = .smtp,
139 /// Accepted at RCPT time and then failed at the end of the message,
140 /// which only LMTP can say.
141 fail_delivery: ?[]const u8 = null,
142 username: ?[]const u8 = null,
143 password: ?[]const u8 = null,
144};
145
146const SendConfig = struct {
147 mode: enum { plain, tls, starttls } = .plain,
148 insecure: bool = false,
149 allow_cleartext_auth: bool = false,
150 chunking: bool = false,
151 smtputf8: bool = false,
152 protocol: zsmtp.Client.Protocol = .smtp,
153 body: ?zsmtp.protocol.Body = null,
154 ret: ?zsmtp.protocol.Ret = null,
155 envid: ?[]const u8 = null,
156 notify: ?zsmtp.protocol.Notify = null,
157 orcpt: ?[]const u8 = null,
158 username: ?[]const u8 = null,
159 password: ?[]const u8 = null,
160 auth_method: enum { auto, plain, login, cram_md5 } = .auto,
161};
162
163fn usage() noreturn {
164 std.log.err(
165 \\usage:
166 \\ zsmtp send [--tls|--starttls] [--insecure] [--allow-cleartext-auth]
167 \\ [--user <u> --password <p>]
168 \\ [--auth-method plain|login|cram-md5]
169 \\ [--ret full|hdrs] [--envid <id>]
170 \\ [--notify never|success,failure,delay] [--orcpt <address>]
171 \\ [--lmtp] [--binarymime] <host> <port> <from> <to>...
172 \\ (message is read from stdin)
173 \\ zsmtp serve [--tls-cert <pem> --tls-key <pem> [--implicit-tls]]
174 \\ [--auth <user>:<pass>] [--lmtp [--fail-delivery <address>]]
175 \\ <port>
176 , .{});
177 std.process.exit(1);
178}
179
180fn send(
181 io: Io,
182 arena: std.mem.Allocator,
183 config: SendConfig,
184 host_arg: []const u8,
185 port_arg: []const u8,
186 from: []const u8,
187 recipients: []const []const u8,
188) !void {
189 const host = try Io.net.HostName.init(host_arg);
190 const port = try std.fmt.parseInt(u16, port_arg, 10);
191
192 var stdin_buf: [4096]u8 = undefined;
193 var stdin: Io.File.Reader = .init(.stdin(), io, &stdin_buf);
194
195 const stream = try host.connect(io, port, .{ .mode = .stream });
196 defer stream.close(io);
197 // The TLS layer requires stream buffers of at least min_buffer_len.
198 const read_buf = try arena.alloc(u8, zsmtp.Tls.min_buffer_len);
199 const write_buf = try arena.alloc(u8, zsmtp.Tls.min_buffer_len);
200 var stream_reader = stream.reader(io, read_buf);
201 var stream_writer = stream.writer(io, write_buf);
202
203 const tls_options: zsmtp.Tls.Options = .{
204 .host = host_arg,
205 .ca = if (config.insecure) .insecure else .system,
206 };
207 var tls: zsmtp.Tls = undefined;
208 var tls_active = false;
209 defer if (tls_active) {
210 tls.end() catch {};
211 tls.deinit(arena);
212 };
213
214 var reply_buf: [1024]u8 = undefined;
215 var client: zsmtp.Client = .init(&stream_reader.interface, &stream_writer.interface, &reply_buf);
216 client.allow_cleartext_auth = config.allow_cleartext_auth;
217 client.mode = config.protocol;
218
219 if (config.mode == .tls) {
220 try tls.init(io, arena, &stream_reader.interface, &stream_writer.interface, tls_options);
221 tls_active = true;
222 client.setTransport(tls.reader(), tls.writer(), .encrypted);
223 }
224
225 _ = try client.greet();
226 var extensions = try client.hello("localhost");
227
228 if (config.mode == .starttls) {
229 try client.starttls();
230 try tls.init(io, arena, &stream_reader.interface, &stream_writer.interface, tls_options);
231 tls_active = true;
232 client.setTransport(tls.reader(), tls.writer(), .encrypted);
233 extensions = try client.hello("localhost");
234 }
235
236 if (config.username) |username| {
237 const password = config.password.?;
238 const result = switch (config.auth_method) {
239 .auto => client.authenticate(extensions, username, password),
240 .plain => client.authPlain("", username, password),
241 .login => client.authLogin(username, password),
242 .cram_md5 => client.authCramMd5(username, password),
243 };
244 result catch |err| {
245 switch (err) {
246 error.AuthenticationFailed => {
247 const reply = client.last_reply.?;
248 std.log.err("authentication failed: {d} {s}", .{ reply.code, reply.text });
249 },
250 error.InsecureTransport => std.log.err(
251 "refusing to send credentials over an unencrypted connection; " ++
252 "use --starttls or --tls, or pass --allow-cleartext-auth",
253 .{},
254 ),
255 else => {},
256 }
257 return err;
258 };
259 }
260
261 if (config.chunking and !extensions.chunking) {
262 std.log.err("server does not advertise CHUNKING", .{});
263 return error.ChunkingNotAdvertised;
264 }
265 if (config.smtputf8 and !extensions.smtputf8) {
266 std.log.err("server does not advertise SMTPUTF8", .{});
267 return error.SmtpUtf8NotAdvertised;
268 }
269 if (config.body == .binary_mime and !extensions.binary_mime) {
270 // RFC 3030 is absolute about this one: without the advertisement,
271 // binary must not be sent under any circumstances.
272 std.log.err("server does not advertise BINARYMIME", .{});
273 return error.BinaryMimeNotAdvertised;
274 }
275 const wants_dsn = config.ret != null or config.envid != null or
276 config.notify != null or config.orcpt != null;
277 if (wants_dsn and !extensions.dsn) {
278 // A conforming server answers an unrecognized parameter with 555,
279 // so this is only a clearer way to say the same thing.
280 std.log.err("server does not advertise DSN", .{});
281 return error.DsnNotAdvertised;
282 }
283 transact(&client, config, from, recipients, &stdin.interface) catch |err| {
284 if (err == error.UnexpectedReply) {
285 const reply = client.last_reply.?;
286 std.log.err("server rejected: {d} {s}", .{ reply.code, reply.text });
287 }
288 return err;
289 };
290 try client.quit();
291 std.log.info("message sent to {d} recipient(s)", .{recipients.len});
292}
293
294/// Runs the mail transaction, streaming the message from `message` so
295/// arbitrarily large input never has to fit in memory.
296fn transact(
297 client: *zsmtp.Client,
298 config: SendConfig,
299 from: []const u8,
300 recipients: []const []const u8,
301 message: *Io.Reader,
302) (zsmtp.Client.Error || zsmtp.Client.ArgumentError)!void {
303 try client.mail(from, .{
304 .smtputf8 = config.smtputf8,
305 .body = config.body,
306 .ret = config.ret,
307 .envid = config.envid,
308 });
309 for (recipients) |recipient| try client.rcpt(recipient, .{
310 .notify = config.notify,
311 .orcpt = if (config.orcpt) |address|
312 .{ .addr_type = "rfc822", .address = address }
313 else
314 null,
315 });
316 if (config.chunking) {
317 // BDAT sends the input verbatim (no line-ending normalization).
318 while (true) {
319 const chunk = message.peekGreedy(1) catch |err| switch (err) {
320 error.EndOfStream => break,
321 error.ReadFailed => return error.ReadFailed,
322 };
323 try client.bdat(chunk, false);
324 message.toss(chunk.len);
325 }
326 try client.bdat("", true);
327 } else {
328 var data_writer = try client.data();
329 while (true) {
330 const chunk = message.peekGreedy(1) catch |err| switch (err) {
331 error.EndOfStream => break,
332 error.ReadFailed => return error.ReadFailed,
333 };
334 try data_writer.interface.writeAll(chunk);
335 message.toss(chunk.len);
336 }
337 // In LMTP there is one verdict per recipient rather than one for
338 // the message, and reporting them individually is the only reason
339 // to be speaking it.
340 var verdicts = try data_writer.endResults();
341 var failed = false;
342 while (try verdicts.next()) |reply| {
343 if (config.protocol == .lmtp) {
344 std.log.info("{s}: {d} {s}", .{
345 recipients[verdicts.index - 1],
346 reply.code,
347 reply.text,
348 });
349 }
350 if (!reply.isPositiveCompletion()) failed = true;
351 }
352 // Each verdict was reported above, so the error only has to say
353 // that one of them was a refusal.
354 if (failed) return if (config.protocol == .lmtp)
355 error.RecipientRejected
356 else
357 error.UnexpectedReply;
358 }
359}
360
361fn serve(io: Io, gpa: std.mem.Allocator, config: ServeConfig, port_arg: []const u8) !void {
362 const port = try std.fmt.parseInt(u16, port_arg, 10);
363 const address: Io.net.IpAddress = .{ .ip4 = .loopback(port) };
364 var listener = try address.listen(io, .{});
365 defer listener.deinit(io);
366
367 var auth: ?zsmtp.tls.config.CertKeyPair = if (config.cert_path) |cert_path|
368 try .fromFilePath(gpa, io, .cwd(), cert_path, config.key_path.?)
369 else
370 null;
371 const tls_options: ?zsmtp.Server.TlsOptions = if (auth) |*a| .{
372 .io = io,
373 .auth = a,
374 .mode = if (config.implicit_tls) .implicit else .starttls,
375 } else null;
376 std.log.info("listening on 127.0.0.1:{d}{s}", .{
377 port,
378 if (tls_options) |t| switch (t.mode) {
379 .starttls => " with STARTTLS",
380 .implicit => " with implicit TLS",
381 } else "",
382 });
383
384 var stdout_buf: [4096]u8 = undefined;
385 var stdout: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
386
387 var printer: MessagePrinter = .{
388 .out = &stdout.interface,
389 .username = config.username,
390 .password = config.password,
391 .fail_delivery = config.fail_delivery,
392 };
393 while (true) {
394 const stream = try listener.accept(io);
395 defer stream.close(io);
396 // Sized for the TLS handshake, which runs over the raw stream.
397 const read_buf = try gpa.alloc(u8, zsmtp.tls.input_buffer_len);
398 defer gpa.free(read_buf);
399 const write_buf = try gpa.alloc(u8, zsmtp.tls.output_buffer_len);
400 defer gpa.free(write_buf);
401 var stream_reader = stream.reader(io, read_buf);
402 var stream_writer = stream.writer(io, write_buf);
403 var session: zsmtp.Server = .init(
404 &stream_reader.interface,
405 &stream_writer.interface,
406 .{ .context = &printer, .vtable = if (config.username != null) &.{
407 .authenticate = MessagePrinter.onAuthenticate,
408 .message = MessagePrinter.onMessage,
409 .recipientResult = MessagePrinter.onRecipientResult,
410 } else &.{
411 .message = MessagePrinter.onMessage,
412 .recipientResult = MessagePrinter.onRecipientResult,
413 } },
414 .{
415 .protocol = config.protocol,
416 .hostname = "localhost",
417 .tls = tls_options,
418 .require_auth = config.username != null,
419 },
420 );
421 session.run(gpa) catch |err| {
422 std.log.warn("session ended with error: {t}", .{err});
423 };
424 }
425}
426
427const MessagePrinter = struct {
428 out: *Io.Writer,
429 username: ?[]const u8 = null,
430 password: ?[]const u8 = null,
431 fail_delivery: ?[]const u8 = null,
432
433 fn onAuthenticate(context: ?*anyopaque, username: []const u8, password: []const u8) bool {
434 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
435 return std.mem.eql(u8, username, printer.username.?) and
436 std.mem.eql(u8, password, printer.password.?);
437 }
438
439 fn onMessage(context: ?*anyopaque, envelope: zsmtp.Server.Envelope, data: []const u8) zsmtp.Server.Decision {
440 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
441 printer.print(envelope, data) catch
442 return .{ .reject = .{ .code = 451, .text = "4.3.0 Local error" } };
443 return .accept;
444 }
445
446 /// LMTP's per-recipient verdict. Everything was already printed by
447 /// `onMessage`; this only reports the one address `--fail-delivery`
448 /// names as undeliverable, which is the outcome SMTP has no way to
449 /// express for one recipient out of several.
450 fn onRecipientResult(
451 context: ?*anyopaque,
452 envelope: zsmtp.Server.Envelope,
453 index: usize,
454 ) zsmtp.Server.Decision {
455 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
456 const failing = printer.fail_delivery orelse return .accept;
457 if (std.mem.eql(u8, envelope.recipients[index].address, failing))
458 return .{ .reject = .{ .code = 550, .text = "5.2.1 Mailbox disabled" } };
459 return .accept;
460 }
461
462 fn print(printer: *MessagePrinter, envelope: zsmtp.Server.Envelope, data: []const u8) !void {
463 try printer.out.print("--- message from <{s}> to", .{envelope.from});
464 for (envelope.recipients) |recipient| {
465 try printer.out.print(" <{s}>", .{recipient.address});
466 // DSN parameters, printed so that a session can be checked from
467 // the outside (which is what the interop test does).
468 if (recipient.notify) |notify| try printer.out.print(" NOTIFY={f}", .{notify});
469 if (recipient.orcpt) |orcpt| try printer.out.print(" ORCPT={f}", .{orcpt});
470 }
471 if (envelope.ret) |ret| try printer.out.print(" RET={f}", .{ret});
472 if (envelope.envid) |envid| try printer.out.print(" ENVID={s}", .{envid});
473 try printer.out.print(" ({d} bytes)\n{s}---\n", .{ data.len, data });
474 try printer.out.flush();
475 }
476};