How do I classify mail with a local machine-learning model?
Since MIMEDefang 3.8, Mail::MIMEDefang::ML asks a
self-hosted model whether a message is spam or phishing. The same code works with every
backend: laya, gliclass or openai (any OpenAI-compatible server). Use it as an
additional opinion, not as a replacement for SpamAssassin or rspamd: a backend that cannot
be reached, or that is not confident enough, returns no verdict, so mail flow is never
blocked.
The Laya and GLiClass model servers are available as the official mimedefang/laya and mimedefang/gliclass Docker images.
use Mail::MIMEDefang::ML;
# Once, at the top of mimedefang-filter
$Mail::MIMEDefang::ML::Config{backend} = 'gliclass'; # or 'laya', 'openai'
$Mail::MIMEDefang::ML::Config{gliclass}{server_url} = 'http://127.0.0.1:8688';
sub filter_end {
my ($entity) = @_;
return if message_rejected();
# $SPFResult, $DKIMResult and $DMARCResult set earlier in the filter
my $verdict = ml_classify(ml_build_state(
Entity => $entity, # headers, subject and body
MailFrom => $Sender,
SPF => $SPFResult,
DKIM => $DKIMResult,
DMARC => $DMARCResult,
));
if ($verdict->{error}) {
md_syslog('info', "ml: no verdict ($verdict->{error})");
return;
}
# answer is 1, 0 or undef (no opinion); confidence is 0.0 .. 1.0
if ($verdict->{is_phishing}{answer}
&& $verdict->{is_phishing}{confidence} >= 0.90) {
md_graphdefang_log('ml_phishing', $verdict->{is_phishing}{confidence});
action_quarantine_entire_message('Suspected phishing');
} elsif ($verdict->{is_spam}{answer}
&& $verdict->{is_spam}{confidence} >= 0.80) {
md_graphdefang_log('ml_spam', $verdict->{is_spam}{confidence});
action_change_header('X-MIMEDefang-ML-Spam', 'yes');
}
action_change_header('X-MIMEDefang-ML-Backend', $verdict->{backend});
}
To use the model only against phishing, ask just that question:
$Mail::MIMEDefang::ML::Config{questions} = ['is_phishing'];
The stock models are not trained on your mail: see "TRAINING A MODEL" in the
man page and contrib/ml-benchmark in the MIMEDefang
sources to measure them against your own corpus. The ml_* events logged above show up in
the Spam & ML view of mimedefang-dashboard.