Adding SpamAssassin to Exim4

After switching to my own imap/smtp hosted solution I noticed that I receveived a LOT of spam.. offcourse all those webmail based solutions (gmail, outlook etc) have their own spam filter. So hosting mail yourself means filtering yourself.. After looking around I found SpamAssassin which includes some nice easy sorting and learning festures.
Here is a quick install guide:

Step 1

Install spamassassin.

1
sudo apt-get install spamassassin

Step 2

Configure Exim4
edit /etc/exim4/exim4.conf.template and uncomment ~line 166

1
spamd_address = 127.0.0.1 783

around line ~930 uncomment

1
2
3
4
5
6
warn
spam = Debian-exim:true
add_header = X-Spam_score: $spam_score\n\
X-Spam_score_int: $spam_score_int\n\
X-Spam_bar: $spam_bar\n\
X-Spam_report: $spam_report

Now exim4 will add a header called X-Spam_score_int to all email in which the score on the spam-scale will be set.
Restart Exim4.

1
sudo service exim4 restart

Step 3

Move all email with a score lower then 50 to a Junk or Spam folder.
Do this by creating a Junk (or whatever you like) folder in your IMAP client.
Now edit the file ~/.forward in your home dir and add the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Exim filter

if error_message then
finish
endif

if
"$h_X-Spam_score_int" is not below 50
then
save $home/Maildir/.Junk/
endif

finish

done.

Step 4 (optional)

Let spamassassin learn from false-positives and new spam email.
Create 2 sub-folders in your ‘Junk’ folder and call then Learn and Forget
Now create a shell script learn.sh somewhere with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/sh

# learn new junk from folder
sa-learn --no-sync --spam --dir /home/<username>/Maildir/.Junk.Learn/{cur,new}
# move learned junk to junk folder
doveadm move -u <username> Junk savedbefore 0d mailbox Junk/Learn

# learn false/positives from forget
sa-learn --no-sync --ham --dir /home/<username>/Maildir/.Junk.Forget/{cur,new}
# move forget email to Inbox
doveadm move -u <username> Inbox savedbefore 0d mailbox Junk/Forget

# sync
sa-learn --sync

# clean Trash and Junk folder
doveadm expunge -u <username> mailbox Trash savedbefore 30d
doveadm expunge -u <username> mailbox Junk savedbefore 14d

# done.
exit 1

Now you can put this script into the crontab to run each hour for instance.

1
0 7-23 * * * /home/<username>/scripts/teach.sh > /dev/null 2>&1

Eveytime a SPAM message ends up in your inbox, just move it to the Junk/Learn folder.
And when you see an important email in your Junk folder, move it to the Junk/Forget folder and it will be placed back into the Inbox within the crontab-time. The SpamAssassin will learn from these things and get better with time.