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 zig-smtp library.
5//!
6//! zig-smtp 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//! zig-smtp 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 smtp = @import("smtp");
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 = smtp.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 = smtp.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: smtp.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: smtp.Client.Protocol = .smtp,
153 body: ?smtp.protocol.Body = null,
154 ret: ?smtp.protocol.Ret = null,
155 envid: ?[]const u8 = null,
156 notify: ?smtp.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 \\ zig-smtp 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 \\ zig-smtp 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, smtp.Tls.min_buffer_len);
199 const write_buf = try arena.alloc(u8, smtp.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: smtp.Tls.Options = .{
204 .host = host_arg,
205 .ca = if (config.insecure) .insecure else .system,
206 };
207 var tls: smtp.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: smtp.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 // The mechanisms come from zig-sasl; what is chosen from them is the
239 // caller's business, and this one lets --auth-method force it.
240 var plain: smtp.sasl.Plain = .init(username, password);
241 var login: smtp.sasl.Login = .init(username, password);
242 var cram_md5: smtp.sasl.CramMd5 = .init(username, password);
243 const offered: []const smtp.sasl.Client = switch (config.auth_method) {
244 // In order of preference, which `selectFromList` reads as such:
245 // PLAIN because every server implements it correctly, CRAM-MD5
246 // last because it is the oldest. On a carrier with no encryption
247 // the first two are skipped and it is the only one left.
248 .auto => &.{ plain.client(), login.client(), cram_md5.client() },
249 .plain => &.{plain.client()},
250 .login => &.{login.client()},
251 .cram_md5 => &.{cram_md5.client()},
252 };
253 const mechanism = smtp.sasl.Client.selectFromList(
254 offered,
255 extensions.auth,
256 client.security == .encrypted or client.allow_cleartext_auth,
257 ) orelse {
258 std.log.err(
259 "no usable mechanism; the server offers: {s}{s}",
260 .{
261 if (extensions.auth.len == 0) "(none)" else extensions.auth,
262 // The common case by far: everything on offer sends the
263 // password, and this connection is not encrypted.
264 if (client.security == .plaintext and !client.allow_cleartext_auth)
265 ", and this connection is not encrypted " ++
266 "(use --starttls or --tls, or --allow-cleartext-auth)"
267 else
268 "",
269 },
270 );
271 return error.NoSupportedMechanism;
272 };
273 client.authenticate(mechanism) catch |err| {
274 switch (err) {
275 error.AuthenticationFailed => {
276 const reply = client.last_reply.?;
277 std.log.err("authentication failed: {d} {s}", .{ reply.code, reply.text });
278 },
279 error.ServerNotAuthenticated => std.log.err(
280 "the server accepted the login without proving itself; " ++
281 "this is not the server it claims to be",
282 .{},
283 ),
284 error.InsecureTransport => std.log.err(
285 "refusing to send credentials over an unencrypted connection; " ++
286 "use --starttls or --tls, or pass --allow-cleartext-auth",
287 .{},
288 ),
289 else => {},
290 }
291 return err;
292 };
293 }
294
295 if (config.chunking and !extensions.chunking) {
296 std.log.err("server does not advertise CHUNKING", .{});
297 return error.ChunkingNotAdvertised;
298 }
299 if (config.smtputf8 and !extensions.smtputf8) {
300 std.log.err("server does not advertise SMTPUTF8", .{});
301 return error.SmtpUtf8NotAdvertised;
302 }
303 if (config.body == .binary_mime and !extensions.binary_mime) {
304 // RFC 3030 is absolute about this one: without the advertisement,
305 // binary must not be sent under any circumstances.
306 std.log.err("server does not advertise BINARYMIME", .{});
307 return error.BinaryMimeNotAdvertised;
308 }
309 const wants_dsn = config.ret != null or config.envid != null or
310 config.notify != null or config.orcpt != null;
311 if (wants_dsn and !extensions.dsn) {
312 // A conforming server answers an unrecognized parameter with 555,
313 // so this is only a clearer way to say the same thing.
314 std.log.err("server does not advertise DSN", .{});
315 return error.DsnNotAdvertised;
316 }
317 transact(&client, config, from, recipients, &stdin.interface) catch |err| {
318 if (err == error.UnexpectedReply) {
319 const reply = client.last_reply.?;
320 std.log.err("server rejected: {d} {s}", .{ reply.code, reply.text });
321 }
322 return err;
323 };
324 try client.quit();
325 std.log.info("message sent to {d} recipient(s)", .{recipients.len});
326}
327
328/// Runs the mail transaction, streaming the message from `message` so
329/// arbitrarily large input never has to fit in memory.
330fn transact(
331 client: *smtp.Client,
332 config: SendConfig,
333 from: []const u8,
334 recipients: []const []const u8,
335 message: *Io.Reader,
336) (smtp.Client.Error || smtp.Client.ArgumentError)!void {
337 try client.mail(from, .{
338 .smtputf8 = config.smtputf8,
339 .body = config.body,
340 .ret = config.ret,
341 .envid = config.envid,
342 });
343 for (recipients) |recipient| try client.rcpt(recipient, .{
344 .notify = config.notify,
345 .orcpt = if (config.orcpt) |address|
346 .{ .addr_type = "rfc822", .address = address }
347 else
348 null,
349 });
350 if (config.chunking) {
351 // BDAT sends the input verbatim (no line-ending normalization).
352 while (true) {
353 const chunk = message.peekGreedy(1) catch |err| switch (err) {
354 error.EndOfStream => break,
355 error.ReadFailed => return error.ReadFailed,
356 };
357 try client.bdat(chunk, false);
358 message.toss(chunk.len);
359 }
360 try client.bdat("", true);
361 } else {
362 var data_writer = try client.data();
363 while (true) {
364 const chunk = message.peekGreedy(1) catch |err| switch (err) {
365 error.EndOfStream => break,
366 error.ReadFailed => return error.ReadFailed,
367 };
368 try data_writer.interface.writeAll(chunk);
369 message.toss(chunk.len);
370 }
371 // In LMTP there is one verdict per recipient rather than one for
372 // the message, and reporting them individually is the only reason
373 // to be speaking it.
374 var verdicts = try data_writer.endResults();
375 var failed = false;
376 while (try verdicts.next()) |reply| {
377 if (config.protocol == .lmtp) {
378 std.log.info("{s}: {d} {s}", .{
379 recipients[verdicts.index - 1],
380 reply.code,
381 reply.text,
382 });
383 }
384 if (!reply.isPositiveCompletion()) failed = true;
385 }
386 // Each verdict was reported above, so the error only has to say
387 // that one of them was a refusal.
388 if (failed) return if (config.protocol == .lmtp)
389 error.RecipientRejected
390 else
391 error.UnexpectedReply;
392 }
393}
394
395fn serve(io: Io, gpa: std.mem.Allocator, config: ServeConfig, port_arg: []const u8) !void {
396 const port = try std.fmt.parseInt(u16, port_arg, 10);
397 const address: Io.net.IpAddress = .{ .ip4 = .loopback(port) };
398 var listener = try address.listen(io, .{});
399 defer listener.deinit(io);
400
401 var auth: ?smtp.tls.config.CertKeyPair = if (config.cert_path) |cert_path|
402 try .fromFilePath(gpa, io, .cwd(), cert_path, config.key_path.?)
403 else
404 null;
405 const tls_options: ?smtp.Server.TlsOptions = if (auth) |*a| .{
406 .io = io,
407 .auth = a,
408 .mode = if (config.implicit_tls) .implicit else .starttls,
409 } else null;
410 std.log.info("listening on 127.0.0.1:{d}{s}", .{
411 port,
412 if (tls_options) |t| switch (t.mode) {
413 .starttls => " with STARTTLS",
414 .implicit => " with implicit TLS",
415 } else "",
416 });
417
418 var stdout_buf: [4096]u8 = undefined;
419 var stdout: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
420
421 var printer: MessagePrinter = .{
422 .out = &stdout.interface,
423 .username = config.username,
424 .password = config.password,
425 .fail_delivery = config.fail_delivery,
426 };
427 while (true) {
428 const stream = try listener.accept(io);
429 defer stream.close(io);
430 // Sized for the TLS handshake, which runs over the raw stream.
431 const read_buf = try gpa.alloc(u8, smtp.tls.input_buffer_len);
432 defer gpa.free(read_buf);
433 const write_buf = try gpa.alloc(u8, smtp.tls.output_buffer_len);
434 defer gpa.free(write_buf);
435 var stream_reader = stream.reader(io, read_buf);
436 var stream_writer = stream.writer(io, write_buf);
437 var session: smtp.Server = .init(
438 &stream_reader.interface,
439 &stream_writer.interface,
440 .{ .context = &printer, .vtable = if (config.username != null) &.{
441 .authenticate = MessagePrinter.onAuthenticate,
442 .message = MessagePrinter.onMessage,
443 .recipientResult = MessagePrinter.onRecipientResult,
444 } else &.{
445 .message = MessagePrinter.onMessage,
446 .recipientResult = MessagePrinter.onRecipientResult,
447 } },
448 .{
449 .protocol = config.protocol,
450 .hostname = "localhost",
451 .tls = tls_options,
452 .require_auth = config.username != null,
453 },
454 );
455 session.run(gpa) catch |err| {
456 std.log.warn("session ended with error: {t}", .{err});
457 };
458 }
459}
460
461const MessagePrinter = struct {
462 out: *Io.Writer,
463 username: ?[]const u8 = null,
464 password: ?[]const u8 = null,
465 fail_delivery: ?[]const u8 = null,
466
467 fn onAuthenticate(context: ?*anyopaque, username: []const u8, password: []const u8) bool {
468 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
469 return std.mem.eql(u8, username, printer.username.?) and
470 std.mem.eql(u8, password, printer.password.?);
471 }
472
473 fn onMessage(context: ?*anyopaque, envelope: smtp.Server.Envelope, data: []const u8) smtp.Server.Decision {
474 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
475 printer.print(envelope, data) catch
476 return .{ .reject = .{ .code = 451, .text = "4.3.0 Local error" } };
477 return .accept;
478 }
479
480 /// LMTP's per-recipient verdict. Everything was already printed by
481 /// `onMessage`; this only reports the one address `--fail-delivery`
482 /// names as undeliverable, which is the outcome SMTP has no way to
483 /// express for one recipient out of several.
484 fn onRecipientResult(
485 context: ?*anyopaque,
486 envelope: smtp.Server.Envelope,
487 index: usize,
488 ) smtp.Server.Decision {
489 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
490 const failing = printer.fail_delivery orelse return .accept;
491 if (std.mem.eql(u8, envelope.recipients[index].address, failing))
492 return .{ .reject = .{ .code = 550, .text = "5.2.1 Mailbox disabled" } };
493 return .accept;
494 }
495
496 fn print(printer: *MessagePrinter, envelope: smtp.Server.Envelope, data: []const u8) !void {
497 try printer.out.print("--- message from <{s}> to", .{envelope.from});
498 for (envelope.recipients) |recipient| {
499 try printer.out.print(" <{s}>", .{recipient.address});
500 // DSN parameters, printed so that a session can be checked from
501 // the outside (which is what the interop test does).
502 if (recipient.notify) |notify| try printer.out.print(" NOTIFY={f}", .{notify});
503 if (recipient.orcpt) |orcpt| try printer.out.print(" ORCPT={f}", .{orcpt});
504 }
505 if (envelope.ret) |ret| try printer.out.print(" RET={f}", .{ret});
506 if (envelope.envid) |envid| try printer.out.print(" ENVID={s}", .{envid});
507 try printer.out.print(" ({d} bytes)\n{s}---\n", .{ data.len, data });
508 try printer.out.flush();
509 }
510};