SpamAssassin spam analyzer script in PHP based on sa-learn command I wrote a small script to analyse spam messages that are spam false negative; meaning that they are spam messages in nature but that happened to be in your INBOX folder because your spam filter failed to detect it correctly (I personally use SpamAssassin and unfortunately it rarely happens).

The goal is to have a chance to analyse spam messages that are put in spam folder manually by running a script in cron jobs.

Obviously, all spam messages will be analysed regardless of which email client you're using (Thunderbird, Kaiten Mail or Roundcube), because all you need is to have a message moved in spam folder.

Example of my well working PHP script:

&lt;?php
// Check if there is messages in SPAM folder that don't have [SPAM] lable (e.g.: manually moved from INBOX)
exec("grep -L '\[SPAM\]' /home/domainexample.ru/Maildir/.Junk/cur/* 2&gt; /dev/null", $spam_messages);

if (!empty($spam_messages)) {

    $sa_learn = '/usr/bin/sa-learn --spam';
    foreach ($spam_messages as $spam_message) {
        //Learn a message that we believe is spam
        $sa_learn .= ' ' . $spam_message;
        $marked_as_spam = file_get_contents($spam_message);
        // Adding [SPAM] flag to message's subject of analyzed message
        $marked_as_spam = str_replace("Subject:", "Subject: [SPAM] ", $marked_as_spam);
        file_put_contents($spam_message, utf8_encode($marked_as_spam));
    }
    // Logging the results
    $sa_learn .= ' &gt; ' . '/home/domainexample.ru/.spamassassin/logs/' . date('d.m.Y-G:i') . '_analyzer.log';
    //Executing analyzer in background 
    shell_exec("nohup $sa_learn 2&gt; /dev/null &amp; echo $!");
    // Cleaning cached messages in Dovecot
    shell_exec("rm -f /var/lib/dovecot/index/domainexample.ru/.Junk/*");
}
?&gt;


I would like to have (in case there are) few ideas for improving this already working PHP script but most importantly, I would like to learn of how to write the same script using PERL or/and BASH scripting.

Could you please suggest some ideas for improving current PHP script, along with providing pure and fully working examples of the same scenarios in PERL or/and BASH?
Here's an untested Bash version:

#!/usr/bin/env bash
set -o errexit -o noclobber -o nounset

while IFS= read -r -u 9 path
do
    /usr/bin/sa-learn --spam "$path" \
        &gt; "/home/domainexample.ru/.spamassassin/logs/$(date +%d.%m.%Y-%G:%S)_analyzer.log" \
        2&gt;&amp;1 &amp;
    sed -i -e 's/^Subject:/Subject: [SPAM] /' "$path"
    rm "$path"
done 9&lt; &lt;(grep -FL '[SPAM]' /home/domainexample.ru/Maildir/.Junk/cur/* 2&gt; /dev/null)


Some changes from the original:


Uses grep's -F option to speed up search.
Runs sa-learn repeatedly instead of once to avoid having to accumulate the data. Shouldn't slow down the execution since the processes are backgrounded.
Deletes files as soon as they are processed, to avoid reprocessing if the previous run failed.