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