1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Command-line entry point.
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use smtp_test_tool::config::{default_save_path, discover_config_path, Config};
use smtp_test_tool::i18n::{self, t};
use smtp_test_tool::keystore::default_keystore;
use smtp_test_tool::locale as os_locale;
use smtp_test_tool::providers::{self, Provider};
use smtp_test_tool::{outlook_defaults, run_tests, Profile};
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use tracing_subscriber::EnvFilter;
#[derive(Parser, Debug)]
#[command(
name = "smtp-test-tool",
version,
about,
long_about = "Test SMTP / IMAP / POP3 connectivity to any mail server.\n\
Defaults to Outlook.com / Office 365."
)]
struct Cli {
/// TOML config file to load.
#[arg(short, long, env = "SMTP_TEST_TOOL_CONFIG")]
config: Option<PathBuf>,
/// Profile within the config file (default: 'default').
#[arg(short, long)]
profile: Option<String>,
/// Username (overrides config).
#[arg(short, long)]
user: Option<String>,
/// Password (omit to prompt).
#[arg(short = 'P', long)]
password: Option<String>,
/// Bearer token for XOAUTH2 (overrides --password).
#[arg(long)]
oauth_token: Option<String>,
/// Apply a built-in provider preset (overwrites smtp/imap/pop3 host,
/// port, and security on the active profile). Run `smtp-test-tool
/// providers` for the list of valid names. Matching is case-insensitive
/// and accepts any unique substring, so `--provider gmail` and
/// `--provider "google workspace"` both pick Gmail.
#[arg(long, value_name = "NAME")]
provider: Option<String>,
/// Look up the password in the OS keychain at startup (Windows
/// Credential Manager / macOS Keychain / Linux Secret Service).
/// Requires --user (or `user = ...` in the loaded profile) so we
/// know which entry to fetch. Silent if nothing is stored.
#[arg(long)]
keychain_load: bool,
/// After a successful run, write the (current) password to the OS
/// keychain under the active user. Combines with --keychain-load
/// to give a 'remember me' workflow: pass --password once with
/// --keychain-save, then --keychain-load on every subsequent run.
#[arg(long)]
keychain_save: bool,
/// Disable certificate verification (testing only).
#[arg(long)]
insecure: bool,
/// Override log level (trace, debug, info, warn, error).
#[arg(long)]
log_level: Option<String>,
/// Force a specific interface language (e.g. en, nl, de). By
/// default the active profile's `locale` field is honoured if set;
/// otherwise the OS locale is auto-detected. Unsupported codes
/// silently fall back to 'en' so the tool always has SOMETHING to
/// say. Run `smtp-test-tool --help` after a future expansion to
/// see the current shipped set, or check the locales/ folder in
/// the repo.
#[arg(long, value_name = "CODE")]
locale: Option<String>,
/// Sub-commands. Default action is 'test' against the loaded profile.
#[command(subcommand)]
cmd: Option<Cmd>,
}
#[derive(Subcommand, Debug)]
enum Cmd {
/// Run the connectivity test (default action).
Test,
/// List profiles in the loaded config file.
Profiles,
/// Print the Outlook.com defaults as a starter TOML.
Init {
/// File to write (default: ./smtp_test_tool.toml).
#[arg(short, long)]
output: Option<PathBuf>,
},
/// List the built-in provider presets that --provider accepts.
Providers,
/// Inspect or manage the OS-keychain entries this tool created.
#[command(subcommand)]
Keychain(KeychainCmd),
}
#[derive(Subcommand, Debug)]
enum KeychainCmd {
/// Test whether an entry exists for USER under the smtp-test-tool
/// service in the OS keychain. Prints 'stored' or 'absent';
/// never prints the secret itself.
Status {
/// Account / email address to look up.
user: String,
},
/// Delete the smtp-test-tool entry for USER from the OS keychain.
/// Idempotent: succeeds even if no entry was stored.
Forget {
/// Account / email address to forget.
user: String,
},
}
fn main() -> ExitCode {
match run() {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::from(1),
Err(e) => {
eprintln!("error: {e:#}");
ExitCode::from(2)
}
}
}
fn run() -> Result<bool> {
let cli = Cli::parse();
// ---- logging --------------------------------------------------------
let lvl = cli.log_level.clone().unwrap_or_else(|| "info".into());
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&lvl));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(false)
.with_level(true)
.with_ansi(supports_colour())
.with_writer(io::stderr)
.init();
// ---- locate config --------------------------------------------------
let cfg_path = cli.config.clone().or_else(discover_config_path);
let cfg = match &cfg_path {
Some(p) => Config::load(p).with_context(|| format!("loading {}", p.display()))?,
None => Config {
active: "default".into(),
profiles: [("default".into(), outlook_defaults())]
.into_iter()
.collect(),
},
};
let profile_name = cli.profile.clone().unwrap_or_else(|| cfg.active.clone());
// Locale resolution mirrors the GUI: explicit --locale wins, then
// Profile.locale, then OS detection, then base 'en'. Applied
// before any subcommand runs so 'providers' / 'keychain status'
// etc. show localised strings too (currently they print English
// sentinels; future expansion can route through t() the same way
// the diagnostic translator already does).
let active_locale: String = {
let candidate = cli
.locale
.clone()
.or_else(|| cfg.profile(&profile_name).and_then(|p| p.locale.clone()));
match candidate {
Some(c) if i18n::is_supported(&c) => c,
_ => match os_locale::detect() {
Some(c) if i18n::is_supported(&c) => c,
_ => i18n::BASE.to_string(),
},
}
};
i18n::set_locale(&active_locale);
match cli.cmd.unwrap_or(Cmd::Test) {
Cmd::Profiles => {
match &cfg_path {
Some(p) => println!("Profiles in {}:", p.display()),
None => println!("No config file loaded; using built-in defaults."),
}
for n in cfg.profile_names() {
println!(" {n}{}", if n == cfg.active { " (active)" } else { "" });
}
return Ok(true);
}
Cmd::Keychain(sub) => {
let ks = default_keystore();
return match sub {
KeychainCmd::Status { user } => {
match ks.load(&user)? {
Some(_) => println!("stored"),
None => println!("absent"),
}
Ok(true)
}
KeychainCmd::Forget { user } => {
ks.forget(&user)
.with_context(|| format!("forgetting keychain entry for {user}"))?;
println!("forgotten ({user})");
Ok(true)
}
};
}
Cmd::Providers => {
println!("Built-in provider presets (use with --provider):");
let mut max_name = 0;
for p in providers::PROVIDERS {
max_name = max_name.max(p.name.len());
}
for p in providers::PROVIDERS {
println!(
" {:<width$} smtp={}:{} imap={}:{}{}",
p.name,
p.smtp.host,
p.smtp.port,
p.imap.host,
p.imap.port,
if p.pop.is_none() { " (no POP3)" } else { "" },
width = max_name
);
if let Some(note) = p.note {
println!(" {:width$} note: {}", "", note, width = max_name);
}
}
return Ok(true);
}
Cmd::Init { output } => {
let mut new_cfg = Config {
active: "default".into(),
profiles: Default::default(),
};
new_cfg.upsert_profile("default", outlook_defaults());
let target = output.unwrap_or_else(default_save_path);
new_cfg.save(&target)?;
println!("Wrote starter config to {}", target.display());
return Ok(true);
}
Cmd::Test => { /* fall through */ }
}
// ---- build the effective profile (CLI overrides config) ------------
let mut profile: Profile = cfg
.profile(&profile_name)
.cloned()
.unwrap_or_else(outlook_defaults);
// Apply --provider BEFORE the credential overrides so user/password
// entered on the command line win over anything the preset implies
// (though presets never populate credentials).
if let Some(name) = cli.provider.as_deref() {
let p = resolve_provider(name)?;
apply_provider_to(&mut profile, p);
tracing::info!("applied provider preset: {}", p.name);
if let Some(note) = p.note {
tracing::info!(" note: {note}");
}
}
if let Some(u) = cli.user {
profile.user = Some(u);
}
if let Some(p) = cli.password {
profile.password = Some(p);
}
if let Some(t) = cli.oauth_token {
profile.oauth_token = Some(t);
}
if cli.insecure {
profile.insecure_tls = true;
}
if profile.user.is_none() {
profile.user = Some(prompt(&t("cli.prompt.username"))?);
}
// Keychain auto-load happens AFTER --password / --oauth-token have
// been merged so an explicit CLI override always wins. Only the
// user-supplied --keychain-load flag triggers the lookup; we don't
// probe the keychain silently on every run.
let keystore = default_keystore();
if cli.keychain_load && profile.password.is_none() && profile.oauth_token.is_none() {
if let Some(user) = &profile.user {
match keystore.load(user) {
Ok(Some(pwd)) => {
tracing::info!("loaded password for {user} from OS keychain");
profile.password = Some(pwd);
}
Ok(None) => {
tracing::info!("no keychain entry for {user} - falling back to prompt");
}
Err(e) => {
tracing::warn!("keychain load failed for {user}: {e:#}");
}
}
}
}
if profile.password.is_none() && profile.oauth_token.is_none() {
profile.password = Some(prompt_password(&t("cli.prompt.password"))?);
}
let results = run_tests(&profile);
// Save AFTER a successful run so we never persist a broken password.
if cli.keychain_save && results.all_passed() {
if let (Some(user), Some(pwd)) = (&profile.user, &profile.password) {
match keystore.save(user, pwd) {
Ok(()) => tracing::info!("saved password for {user} to OS keychain"),
Err(e) => tracing::warn!("keychain save failed for {user}: {e:#}"),
}
}
}
Ok(results.all_passed())
}
/// Resolve a `--provider` argument to a curated preset. Case-insensitive
/// exact match first, then case-insensitive unique-substring match.
/// Ambiguous matches are an error rather than silently picking the first.
fn resolve_provider(name: &str) -> Result<&'static Provider> {
let needle = name.to_ascii_lowercase();
// 1. Exact match (case-insensitive).
if let Some(p) = providers::PROVIDERS
.iter()
.find(|p| p.name.eq_ignore_ascii_case(name))
{
return Ok(p);
}
// 2. Unique substring match.
let hits: Vec<&'static Provider> = providers::PROVIDERS
.iter()
.filter(|p| p.name.to_ascii_lowercase().contains(&needle))
.collect();
match hits.len() {
1 => Ok(hits[0]),
0 => Err(anyhow::anyhow!(
"unknown provider {name:?}; run `smtp-test-tool providers` for the list"
)),
_ => {
let names: Vec<&str> = hits.iter().map(|p| p.name).collect();
Err(anyhow::anyhow!(
"provider {name:?} is ambiguous; matched: {}",
names.join(", ")
))
}
}
}
/// Mirror of GUI's `App::apply_provider`, on a free-standing Profile.
fn apply_provider_to(profile: &mut Profile, p: &Provider) {
profile.smtp_host = p.smtp.host.into();
profile.smtp_port = p.smtp.port;
profile.smtp_security = p.smtp.security;
profile.imap_host = p.imap.host.into();
profile.imap_port = p.imap.port;
profile.imap_security = p.imap.security;
match p.pop {
Some(pop) => {
profile.pop_host = pop.host.into();
profile.pop_port = pop.port;
profile.pop_security = pop.security;
}
None => {
profile.pop_enabled = false;
}
}
}
fn prompt(msg: &str) -> Result<String> {
print!("{msg}");
io::stdout().flush().ok();
let mut s = String::new();
io::stdin().read_line(&mut s)?;
Ok(s.trim().to_string())
}
fn prompt_password(msg: &str) -> Result<String> {
// Minimal "hidden" prompt - on Windows / Unix we just read a line and
// hope the terminal is not echoing. Pulling in `rpassword` would add
// another dep; for an internal tool the trade-off is fine.
eprint!("{msg}");
io::stderr().flush().ok();
let mut s = String::new();
io::stdin().read_line(&mut s)?;
Ok(s.trim_end_matches(['\r', '\n']).to_string())
}
fn supports_colour() -> bool {
if std::env::var_os("NO_COLOR").is_some() {
return false;
}
// tracing_subscriber's ansi detection is conservative on Windows;
// we trust stderr being a TTY.
use std::io::IsTerminal;
io::stderr().is_terminal()
}