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] [--chunking]
7//! [--user <u> --password <p>]
8//! [--auth-method plain|login|cram-md5] <host> <port> <from> <to>...
9//! send a message read from stdin; --tls speaks TLS from the first
10//! byte (port 465 style), --starttls upgrades after EHLO (port 587
11//! style), --insecure skips certificate verification, --user/--password
12//! authenticate with the best advertised mechanism (or the one forced
13//! by --auth-method)
14//! zsmtp serve [--tls-cert <pem> --tls-key <pem> [--implicit-tls]]
15//! [--auth <user>:<pass>] <port>
16//! run a debug server on 127.0.0.1 that prints received messages;
17//! --auth requires authentication with the given credentials; with a
18//! certificate and key it advertises and accepts STARTTLS, or speaks
19//! TLS from the first byte with --implicit-tls
20
21const std = @import("std");
22const Io = std.Io;
23const zsmtp = @import("zsmtp");
24
25pub fn main(init: std.process.Init) !void {
26 const arena = init.arena.allocator();
27 const io = init.io;
28 const args = try init.minimal.args.toSlice(arena);
29
30 if (args.len >= 2 and std.mem.eql(u8, args[1], "send")) {
31 var config: SendConfig = .{};
32 var rest = args[2..];
33 while (rest.len > 0 and std.mem.startsWith(u8, rest[0], "--")) {
34 if (std.mem.eql(u8, rest[0], "--tls")) {
35 config.mode = .tls;
36 } else if (std.mem.eql(u8, rest[0], "--starttls")) {
37 config.mode = .starttls;
38 } else if (std.mem.eql(u8, rest[0], "--insecure")) {
39 config.insecure = true;
40 } else if (std.mem.eql(u8, rest[0], "--chunking")) {
41 config.chunking = true;
42 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--user")) {
43 config.username = rest[1];
44 rest = rest[1..];
45 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--password")) {
46 config.password = rest[1];
47 rest = rest[1..];
48 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--auth-method")) {
49 config.auth_method = std.meta.stringToEnum(
50 @TypeOf(config.auth_method),
51 rest[1],
52 ) orelse if (std.mem.eql(u8, rest[1], "cram-md5")) .cram_md5 else return usage();
53 rest = rest[1..];
54 } else {
55 return usage();
56 }
57 rest = rest[1..];
58 }
59 if ((config.username == null) != (config.password == null)) return usage();
60 if (rest.len < 4) return usage();
61 return send(io, arena, config, rest[0], rest[1], rest[2], rest[3..]);
62 }
63 if (args.len >= 2 and std.mem.eql(u8, args[1], "serve")) {
64 var config: ServeConfig = .{};
65 var rest = args[2..];
66 while (rest.len > 0 and std.mem.startsWith(u8, rest[0], "--")) {
67 if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--tls-cert")) {
68 config.cert_path = rest[1];
69 rest = rest[1..];
70 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--tls-key")) {
71 config.key_path = rest[1];
72 rest = rest[1..];
73 } else if (rest.len >= 2 and std.mem.eql(u8, rest[0], "--auth")) {
74 const sep = std.mem.indexOfScalar(u8, rest[1], ':') orelse return usage();
75 config.username = rest[1][0..sep];
76 config.password = rest[1][sep + 1 ..];
77 rest = rest[1..];
78 } else if (std.mem.eql(u8, rest[0], "--implicit-tls")) {
79 config.implicit_tls = true;
80 } else {
81 return usage();
82 }
83 rest = rest[1..];
84 }
85 if (rest.len != 1) return usage();
86 if ((config.cert_path == null) != (config.key_path == null)) return usage();
87 if (config.implicit_tls and config.cert_path == null) return usage();
88 return serve(io, arena, config, rest[0]);
89 }
90 return usage();
91}
92
93const ServeConfig = struct {
94 cert_path: ?[]const u8 = null,
95 key_path: ?[]const u8 = null,
96 implicit_tls: bool = false,
97 username: ?[]const u8 = null,
98 password: ?[]const u8 = null,
99};
100
101const SendConfig = struct {
102 mode: enum { plain, tls, starttls } = .plain,
103 insecure: bool = false,
104 chunking: bool = false,
105 username: ?[]const u8 = null,
106 password: ?[]const u8 = null,
107 auth_method: enum { auto, plain, login, cram_md5 } = .auto,
108};
109
110fn usage() noreturn {
111 std.log.err(
112 \\usage:
113 \\ zsmtp send [--tls|--starttls] [--insecure] [--user <u> --password <p>]
114 \\ [--auth-method plain|login|cram-md5] <host> <port> <from> <to>...
115 \\ (message is read from stdin)
116 \\ zsmtp serve [--tls-cert <pem> --tls-key <pem> [--implicit-tls]]
117 \\ [--auth <user>:<pass>] <port>
118 , .{});
119 std.process.exit(1);
120}
121
122fn send(
123 io: Io,
124 arena: std.mem.Allocator,
125 config: SendConfig,
126 host_arg: []const u8,
127 port_arg: []const u8,
128 from: []const u8,
129 recipients: []const []const u8,
130) !void {
131 const host = try Io.net.HostName.init(host_arg);
132 const port = try std.fmt.parseInt(u16, port_arg, 10);
133
134 var stdin_buf: [4096]u8 = undefined;
135 var stdin: Io.File.Reader = .init(.stdin(), io, &stdin_buf);
136
137 const stream = try host.connect(io, port, .{ .mode = .stream });
138 defer stream.close(io);
139 // The TLS layer requires stream buffers of at least min_buffer_len.
140 const read_buf = try arena.alloc(u8, zsmtp.Tls.min_buffer_len);
141 const write_buf = try arena.alloc(u8, zsmtp.Tls.min_buffer_len);
142 var stream_reader = stream.reader(io, read_buf);
143 var stream_writer = stream.writer(io, write_buf);
144
145 const tls_options: zsmtp.Tls.Options = .{
146 .host = host_arg,
147 .ca = if (config.insecure) .insecure else .system,
148 };
149 var tls: zsmtp.Tls = undefined;
150 var tls_active = false;
151 defer if (tls_active) {
152 tls.end() catch {};
153 tls.deinit(arena);
154 };
155
156 var reply_buf: [1024]u8 = undefined;
157 var client: zsmtp.Client = .init(&stream_reader.interface, &stream_writer.interface, &reply_buf);
158
159 if (config.mode == .tls) {
160 try tls.init(arena, io, &stream_reader.interface, &stream_writer.interface, tls_options);
161 tls_active = true;
162 client.setTransport(tls.reader(), tls.writer());
163 }
164
165 _ = try client.greet();
166 var extensions = try client.hello("localhost");
167
168 if (config.mode == .starttls) {
169 try client.starttls();
170 try tls.init(arena, io, &stream_reader.interface, &stream_writer.interface, tls_options);
171 tls_active = true;
172 client.setTransport(tls.reader(), tls.writer());
173 extensions = try client.hello("localhost");
174 }
175
176 if (config.username) |username| {
177 const password = config.password.?;
178 const result = switch (config.auth_method) {
179 .auto => client.authenticate(extensions, username, password),
180 .plain => client.authPlain("", username, password),
181 .login => client.authLogin(username, password),
182 .cram_md5 => client.authCramMd5(username, password),
183 };
184 result catch |err| {
185 if (err == error.AuthenticationFailed) {
186 const reply = client.last_reply.?;
187 std.log.err("authentication failed: {d} {s}", .{ reply.code, reply.text });
188 }
189 return err;
190 };
191 }
192
193 if (config.chunking and !extensions.chunking) {
194 std.log.err("server does not advertise CHUNKING", .{});
195 return error.ChunkingNotAdvertised;
196 }
197 transact(&client, from, recipients, &stdin.interface, config.chunking) catch |err| {
198 if (err == error.UnexpectedReply) {
199 const reply = client.last_reply.?;
200 std.log.err("server rejected: {d} {s}", .{ reply.code, reply.text });
201 }
202 return err;
203 };
204 try client.quit();
205 std.log.info("message sent to {d} recipient(s)", .{recipients.len});
206}
207
208/// Runs the mail transaction, streaming the message from `message` so
209/// arbitrarily large input never has to fit in memory.
210fn transact(
211 client: *zsmtp.Client,
212 from: []const u8,
213 recipients: []const []const u8,
214 message: *Io.Reader,
215 chunking: bool,
216) zsmtp.Client.Error!void {
217 try client.mailFrom(from);
218 for (recipients) |recipient| try client.rcptTo(recipient);
219 if (chunking) {
220 // BDAT sends the input verbatim (no line-ending normalization).
221 while (true) {
222 const chunk = message.peekGreedy(1) catch |err| switch (err) {
223 error.EndOfStream => break,
224 error.ReadFailed => return error.ReadFailed,
225 };
226 try client.bdat(chunk, false);
227 message.toss(chunk.len);
228 }
229 try client.bdat("", true);
230 } else {
231 try client.sendMessageReader(message);
232 }
233}
234
235fn serve(io: Io, gpa: std.mem.Allocator, config: ServeConfig, port_arg: []const u8) !void {
236 const port = try std.fmt.parseInt(u16, port_arg, 10);
237 const address: Io.net.IpAddress = .{ .ip4 = .loopback(port) };
238 var listener = try address.listen(io, .{});
239 defer listener.deinit(io);
240
241 var auth: ?zsmtp.tls.config.CertKeyPair = if (config.cert_path) |cert_path|
242 try .fromFilePath(gpa, io, .cwd(), cert_path, config.key_path.?)
243 else
244 null;
245 const tls_options: ?zsmtp.Server.TlsOptions = if (auth) |*a| .{
246 .io = io,
247 .auth = a,
248 .mode = if (config.implicit_tls) .implicit else .starttls,
249 } else null;
250 std.log.info("listening on 127.0.0.1:{d}{s}", .{
251 port,
252 if (tls_options) |t| switch (t.mode) {
253 .starttls => " with STARTTLS",
254 .implicit => " with implicit TLS",
255 } else "",
256 });
257
258 var stdout_buf: [4096]u8 = undefined;
259 var stdout: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
260
261 var printer: MessagePrinter = .{
262 .out = &stdout.interface,
263 .username = config.username,
264 .password = config.password,
265 };
266 while (true) {
267 const stream = try listener.accept(io);
268 defer stream.close(io);
269 // Sized for the TLS handshake, which runs over the raw stream.
270 const read_buf = try gpa.alloc(u8, zsmtp.tls.input_buffer_len);
271 defer gpa.free(read_buf);
272 const write_buf = try gpa.alloc(u8, zsmtp.tls.output_buffer_len);
273 defer gpa.free(write_buf);
274 var stream_reader = stream.reader(io, read_buf);
275 var stream_writer = stream.writer(io, write_buf);
276 var session: zsmtp.Server = .init(
277 &stream_reader.interface,
278 &stream_writer.interface,
279 .{ .context = &printer, .vtable = if (config.username != null) &.{
280 .authenticate = MessagePrinter.onAuthenticate,
281 .message = MessagePrinter.onMessage,
282 } else &.{
283 .message = MessagePrinter.onMessage,
284 } },
285 .{
286 .hostname = "localhost",
287 .tls = tls_options,
288 .require_auth = config.username != null,
289 },
290 );
291 session.run(gpa) catch |err| {
292 std.log.warn("session ended with error: {t}", .{err});
293 };
294 }
295}
296
297const MessagePrinter = struct {
298 out: *Io.Writer,
299 username: ?[]const u8 = null,
300 password: ?[]const u8 = null,
301
302 fn onAuthenticate(context: ?*anyopaque, username: []const u8, password: []const u8) bool {
303 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
304 return std.mem.eql(u8, username, printer.username.?) and
305 std.mem.eql(u8, password, printer.password.?);
306 }
307
308 fn onMessage(context: ?*anyopaque, envelope: zsmtp.Server.Envelope, data: []const u8) zsmtp.Server.Decision {
309 const printer: *MessagePrinter = @ptrCast(@alignCast(context.?));
310 printer.print(envelope, data) catch
311 return .{ .reject = .{ .code = 451, .text = "4.3.0 Local error" } };
312 return .accept;
313 }
314
315 fn print(printer: *MessagePrinter, envelope: zsmtp.Server.Envelope, data: []const u8) !void {
316 try printer.out.print("--- message from <{s}> to", .{envelope.from});
317 for (envelope.recipients) |recipient| {
318 try printer.out.print(" <{s}>", .{recipient});
319 }
320 try printer.out.print(" ({d} bytes)\n{s}---\n", .{ data.len, data });
321 try printer.out.flush();
322 }
323};