Rspamd with Postfix and Dovecot in Debian Stretch

As far as spam filters go, SpamAssassin isn’t terrible – but it’s slow and chews through more CPU than I’d like. As I needed to set up a new mail server, I decided to look for alternatives – and after reading many positive reviews, I decided to have a go at running Rspamd instead of setting up SpamAssassin again. I was also able to do away with Policyd-SPF/OpenDKIM/OpenDMARC, as Rspamd handles all these functions as well!

Like pretty much every other antispam suite, Rspamd needs quite a bit of configuration – here are my notes for a minimally configured setup that seems to do a decent job. For larger servers with a higher email volume, further tuning will almost certainly be required – but this should get you going.


Here’s what you should already have:

  • A Debian Stretch server with Internet access
    (this guide will probably also work on Debian Jessie and versions of Ubuntu, but I haven’t tested it)
  • A functioning LAMP stack
    (note that I’m using Apache rather than nginx)
  • Postfix and Dovecot already configured and delivering mail
    (I recommend Christoph Hass’ ISPMail tutorials – just skip the Spamassassin instructions)
  • Ability to update DNS records for your domain(s)
  • Knowledge of how and when to use sudo


Here’s what you need to do:

Install Rspamd and Redis

Note: if you’re following the ISPMail guide (or other similar guide) for Postfix and Dovecot, don’t install spamassassin or spamass-milter!

The packages for Rspamd in Stretch are out of date and unsupported – add the official Rspamd repository before installing Rspamd and Redis.

First, create /etc/apt/sources.list.d/rspamd.list and add the following line (you’ll need to change the release code name if you’re not using Stretch):

deb stretch main

Next, get the GPG key and install stuff:

apt-key add gpg.key
apt-get update
apt-get install rspamd redis-server

Create config files for Rspamd and Redis

First, create a secure password for the Rspamd controller using rspamadm – you’ll need the output from this command in one of the config files:

rspamadm pw

Next, create a bunch of config files – these can be adjusted to taste, but the aim here is a minimal config to get things up and running – you can check the official documentation for additional options.

Set host and port for the main Rspamd worker:

bind_socket = "localhost:11333";

Configure the Rspamd proxy to talk to Postfix via a milter:

bind_socket = "localhost:11332";
milter = yes;
timeout = 120s;
upstream "local" {
  default = yes;
  self_scan = yes;

Configure a socket for the Rspamd controller (used for the web interface and for Dovecot sieve filters). This is where you use the password generated by rspamadm earlier – you may want to use separate standard and “enable” (superuser) passwords:

password = "$2$s164jny.....";
enable_password = "$2$s164jny.....";
bind_socket = "localhost:11334";

Make the Rspamd bayes classifier use Redis:

servers = "";
backend = "redis";
autolearn = true;

Choose which headers get added to emails. This is a matter of personal taste, but I like the following as it’s not too verbose:

use = ["authentication-results", "x-spam-status"];
authenticated_headers = ["authentication-results"];

If a user has replied to an email, don’t mark other emails in the same thread as spam:

action = "no action";

Add URL redirect checks to the URL blacklist check – note that hitting some of these blacklist services more frequently might require purchasing a license:

redirector_hosts_map = "/etc/rspamd/";

Assign dynamic reputation to certain TLDs:

enabled = true;

Cache URL tags in Redis:

enabled = true;

Where to find Redis:

servers = "";

Now we know where to find Redis, adjust Redis’ configuration so it binds to the appropriate IP addresses and is a little less memory hungry – /etc/redis/redis.conf already exists, you just need to adjust one line and add two others:

bind ::1
maxmemory 500mb
maxmemory-policy volatile-lru

A couple other configuration items to consider –

Configure a local DNS resolver – not really necessary for low volumes of mail, as Rspamd will use whatever is in /etc/resolv.conf – however for higher volumes of mail, install something like Unbound and then:

dns {
  nameserver = [""];

Check for phishing emails. Phishing checks chew up an insane amount of memory (~800 MB for the few minutes I had it switched on), so you may not want this..:

openphish_enabled = true;
phishtank_enabled = true;

Get Postfix talking to Rspamd

We’ve already set up Rspamd to talk to Postfix via the milter protocol – now we need to set up Postfix to join the conversation. Update /etc/postfix/ – if you already have a milter section, it will need to be adjusted:

milter_protocol = 6
milter_default_action = accept
smtpd_milters = inet:localhost:11332
non_smtpd_milters = $smtpd_milters
milter_mail_macros =  i {mail_addr} {client_addr} {client_name} {auth_authen}

Now that Rspamd and Postfix are talking to each other, restart both services. New inbound email should have headers like “X-Spam-Status:” added by Rspamd.

systemctl restart postfix
systemctl restart rspamd

Get Dovecot’s sieve and imapsieve plugins to train Rspamd

If Rspamd gets spam detection wrong for a given email, users can retrain Rspamd themselves by moving the email either out of the Junk folder or into the Junk folder as appropriate.

First, enable a couple sieve plugins within the protocol imap { } and protocol lmtp { } sections:


protocol imap {
  mail_plugins = $mail_plugins imap_sieve


protocol lmtp {
  mail_plugins = $mail_plugins sieve

Next, create a directory for the sieve filters:

mkdir /etc/dovecot/sieve

Tell Dovecot to pay attention to emails being shifted between folders and to trigger the sieve filters:


plugin {
  sieve_plugins = sieve_imapsieve sieve_extprograms

  # From elsewhere to Junk folder
  imapsieve_mailbox1_name = Junk
  imapsieve_mailbox1_causes = COPY
  imapsieve_mailbox1_before = file:/etc/dovecot/sieve/report-spam.sieve

  # From Junk folder to elsewhere
  imapsieve_mailbox2_name = *
  imapsieve_mailbox2_from = Junk
  imapsieve_mailbox2_causes = COPY
  imapsieve_mailbox2_before = file:/etc/dovecot/sieve/report-ham.sieve

  sieve_pipe_bin_dir = /etc/dovecot/sieve

  sieve_global_extensions = +vnd.dovecot.pipe

Create the relevant sieve filters:


require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];

if environment :matches "" "*" {
  set "email" "${1}";

pipe :copy "" [ "${email}" ];


require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];

if environment :matches "imap.mailbox" "*" {
  set "mailbox" "${1}";

if string "${mailbox}" "Trash" {

if environment :matches "imap.user" "*" {
  set "username" "${1}";

pipe :copy "" [ "${email}" ];

Restart Dovecot, then compile the two sieve filters:

systemctl restart dovecot
sievec /etc/dovecot/sieve/report-spam.sieve
sievec /etc/dovecot/sieve/report-ham.sieve

Finally, add the scripts referenced in the sieve filters that tell Rspamd to learn as spam or learn as ham:


exec /usr/bin/rspamc -h localhost:11334 learn_spam


exec /usr/bin/rspamc -h localhost:11334 learn_ham

Make the scripts executable, then restart Dovecot one more time:

chmod 755 /etc/dovecot/sieve/
chmod 755 /etc/dovecot/sieve/
systemctl restart dovecot

Create SPF records for your domain

Configuring outbound SPF involves working out what mail servers you could potentially send through and then crafting an appropriate DNS TXT record (note that DNS SPF records have been deprecated and shouldn’t be used).

There are plenty of decent wizards and tutorials out there, but I like the easySPF wizard. Because I run my own mail server and never, ever send through any other mail service, my record looks like this: IN TXT "v=spf1 mx -all"

If I also wanted to use Gmail or Google Apps to send email from my domain, I’d need to change it to look like this: IN TXT "v=spf1 mx -all"

Configure DKIM signing in Rspamd

DKIM won’t improve spam detection rates, so this section can be skipped – but valid DKIM signatures are often used by antispam systems as a negative score, so it may improve delivery rates for your outbound email.

Thankfully, DKIM signing in Rspamd is even easier than setting up OpenDKIM! Create a directory for DKIM keys and then generate a key – I’ve used the domain name in the file name (this makes it easier to have different keys for different domains), and I’m using “dkim” as a selector (use something like the server name for multi-server configs) – adjust the file name in the command below to taste:

sudo mkdir /var/lib/rspamd/dkim
sudo rspamadm dkim_keygen -k /var/lib/rspamd/dkim/ -b 2048 -s dkim -d

The rspamadm dkim_keygen command above will create the private key file and display the public key for the DNS TXT record on screen – the public key isn’t saved anywhere, so add the DNS TXT record immediately as follows:

  • The name of the record should be the selector, followed by _domainkey, followed by the domain
    (so for this example).
  • The value for the record needs to be copied carefully – the three lines should end up on a single line in the record, with spaces in between each: IN TXT "v=DKIM1; k=rsa;" "p=MIIBI.....HtByA" "504pO.....DAQAB"

Protect the private key:

chown -R _rspamd._rspamd /var/lib/rspamd/dkim
chmod 640 /var/lib/rspamd/dkim/

Enable DKIM signing and ARC signing in Rspamd with two new config files – both files have the same content, but they both need to exist. Note that both the domain and selector are called out – this is to allow for multiple domains and different keys. Additionally, allow username mismatches when signing:

path = "/var/lib/rspamd/dkim/$domain.$selector.key";
selector = "dkim";
allow_username_mismatch = true;

Restart Rspamd:

systemctl restart rspamd

It’s extremely important to test the SPF and DKIM setup at this point – don’t just assume everything is working. Incorrect SPF/DKIM configs will break email delivery.

First, wait for your DNS updates to propagate – then check the SPF record and the DKIM record to make sure they are valid.

If these checks pass, use to ensure that outbound mail is being correctly signed.

Configure Apache to reverse proxy Rspamd’s web interface

If you’ve already got admin websites up and running, add access to the shiny Rspamd web interface by using an Apache reverse proxy – first, enable two Apache modules:

a2enmod proxy
a2enmod proxy_http

Add the following to an existing virtual host – the Rspamd web interface will be available at (note the trailing slash):

RewriteEngine On
RewriteRule ^/rspamd/(.*)$1 [P,L]
<Location /rspamd>
  Options FollowSymLinks
  Require all granted

Restart Apache:

systemctl restart apache2

Train Rspamd with existing ham/spam corpora

Rspamd works without training – but training will definitely improve accuracy! For my training, I used the contents of my Inbox as a source of ham and the contents of my Junk folder as a source of spam – modify the following to suit your environment:

rspamc learn_ham /var/vmail/
rspamc learn_spam /var/vmail/

You will probably get a few errors during the training process – some of the more common ones include:

  • <MessageID> contains less tokens than required for bayes classifier
    (the email was too short to classify)
  • <MessageID> has been already learned as ham, ignore it
    (means exactly what it says – the email is similar enough to one already in the database)

Acquire spam for additional training

If you’re like me, you have lots of ham for training purposes – but you’ve deleted most of your spam. It’s important to train both, so you really need some recent spam to tell Rspamd what to look for (old spam isn’t as useful, as spam changes over time).

Art Invoice make their spam corpora available to download – each day has a gzipped file filled with fresh spam ready to train with! Just one problem – it’s in mbox format, rather than Maildir format.

I found a python script to convert mbox files to Maildirs on GitHub – grab that, call it, make it executable and then put it in the same folder as this shell script (which needs to be executable as well):


spamfile=spam--`date '+%Y-%m-%d'`.gz
spamfile_unpacked=spam--`date '+%Y-%m-%d'`
gunzip $spamfile
./ -i $spamfile_unpacked -o spam/
rspamc learn_spam spam/cur/
rm -r $spamfile_unpacked spam/
exit 0

Run it once (as root) to test, then add it to cron for automated daily spam training. Rspamd will already detect most of the messages as spam – you’ll see errors like this:

HTTP error: 410, <MessageID> is skipped for bayes classifier: already in class spam; probability 100.00%

..but there will be enough that get learned to make this a worthwhile exercise.

Filter everyone’s spam into the Junk folder

This step is definitely optional and I’d recommend holding off on this until you’re comfortable that Rspamd is doing a good job of detecting spam.

Out of the box, Rspamd has a few too many false positives for my liking – so I decided to raise the score at which the X-Spam: Yes header gets added from 6 to 8. You can modify this setting with the Rspamd web interface, in the Configuration tab (it’s the setting called “Probably Spam”). I’d recommend adjusting this before creating the following global sieve filter..

First, edit /etc/dovecot/conf.d/90-sieve.conf and add the following line:

sieve_after = /etc/dovecot/sieve/after.d/

Create the directory mentioned above:

mkdir /etc/dovecot/sieve/after.d/

Create the sieve filter – /etc/dovecot/sieve/after.d/junk.sieve

require ["fileinto","mailbox"];
if header :contains "X-Spam" "Yes" {
 fileinto :create "Junk";

Finally, compile the sieve filter, update privileges and restart Dovecot:

sievec /etc/dovecot/sieve/after.d/junk.sieve
chown -R vmail.vmail /etc/dovecot/sieve/
systemctl restart dovecot

References and notes

I couldn’t have written this guide without extensive Googling – among other sites, these were the most helpful:

I will probably tweak this guide as I learn more about Rspamd – I will note any updates I make here.

  • 2017-10-15: Added notes on how to acquire additional spam for training purposes
  • 2017-10-17: Included instructions for enabling the Dovecot imap_sieve and sieve plugins
  • 2017-10-17: Simplified worker controller configuration to use a single bind_socket
  • 2018-01-28: Updated Apache proxy configuration to remove redundant config option
  • 2018-06-05: Change privileges on the Dovecot sieve script directory

Any feedback is greatly appreciated – I hope you find this guide useful!

Postfix with SPF, DKIM and DMARC

Using the tutorials at for setting up Postfix with virtual users and domains is generally excellent, but the tutorial for Debian Jessie (with Postfix 2.11) doesn’t contain instructions for setting up authenticated mail delivery (SPF, DKIM and DMARC). Here are my notes:


  • An otherwise-functioning email setup (these notes build on the tutorial)
  • Understanding of (and ability to modify) DNS records

Inbound SPF

SPF has its pros and cons, but on the whole it’s pretty useful. I’d recommend configuring inbound SPF checks to only reject mail that has a “hard fail” for SPF (vs. “soft fail” or “neutral”).

Install the following:

sudo aptitude install postfix-policyd-spf-python

In /etc/postfix/, in the section shown below – add the check_policy_service line before any RBL checks:

smtpd_recipient_restrictions =
  check_policy_service unix:private/policy-spf

Other SPF tutorials recommend extending the SPF time limit to 3600 seconds (from a default of 1000 seconds) – assuming your server is on a decently quick connection, I can’t see a good reason to change the default.

In /etc/postfix/, enable the SPF service as follows:

policy-spf unix -       n       n       -       -       spawn
  user=nobody argv=/usr/bin/policyd-spf

In /etc/postfix-policyd-spf-python/policyd-spf.conf, ensure the configuration is set to only reject messages that “hard fail” the SPF check – remove the existing HELO_reject line and replace as follows:

HELO_reject = Fail

Restart postfix:

sudo systemctl restart postfix

Send yourself a test email (from Gmail or similar) to ensure you’re getting lines like this in your mail.log:

policyd-spf[22747]: None; identity=helo; client-ip=2607:f8b0:4003:c06::230;;;
policyd-spf[22747]: Pass; identity=mailfrom; client-ip=2607:f8b0:4003:c06::230;;;

Outbound SPF

Configuring outbound SPF involves working out what mail servers you could potentially send through and then crafting an appropriate DNS TXT record (note that DNS SPF records have been deprecated and shouldn’t be used).

There are plenty of decent wizards and tutorials out there, but I like the easySPF wizard. Because I run my own mail server and never, ever send through any other mail service, my record looks like this: IN TXT "v=spf1 mx -all"

If I also wanted to use Gmail or Google Apps to send email from my domain, I’d need to change it to look like this: IN TXT "v=spf1 mx -all"

You can absolutely break mail delivery for your domain using SPF, so it’s really important to understand what you’re putting in to your DNS records.


DKIM is much, much easier than it used to be – and is becoming more and more important in the fight against spam. For a more comprehensive introduction, Eric Allman from Sendmail put together a nice overview of DKIM.

Different tutorials use different packages – I install the following:

sudo aptitude install opendkim opendkim-tools libmail-dkim-perl libcrypt-openssl-random-perl libcrypt-openssl-rsa-perl

The first two packages install OpenDKIM; the remaining packages are so SpamAssassin can handle DKIM signed messages.

Make sure the following directories exist (create them if they don’t):

sudo mkdir /etc/opendkim
sudo mkdir /etc/opendkim/keys

My /etc/opendkim.conf file is as follows. You’ll note that it differs from other tutorials in two main ways:

  • I’m using virtual domains, so I’m not putting everything in the main configuration file
  • I’m not using PID files to communicate with Postfix, so I don’t have things like UMask and PidFile set
AutoRestart             yes
AutoRestartRate         10/1h

Syslog                  yes
SyslogSuccess           yes
LogWhy                  yes

Canonicalization        relaxed/simple

ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts
InternalHosts           refile:/etc/opendkim/TrustedHosts
KeyTable                refile:/etc/opendkim/KeyTable
SigningTable            refile:/etc/opendkim/SigningTable

Mode                    sv
SignatureAlgorithm      rsa-sha256

UserID                  opendkim:opendkim

Socket                  inet:12345@localhost

OversignHeaders         From

Note the Socket line above – that needs to be configured elsewhere as well.

In /etc/default/opendkim, comment out everything except the following:

SOCKET="inet:12345@localhost" # listen on loopback on port 12345

In /etc/postfix/

milter_protocol = 6
milter_default_action = accept
smtpd_milters = inet:localhost:12345
non_smtpd_milters = $smtpd_milters

If you’ve followed the tutorial, you will already have smtpd_milters = unix:/spamass/spamass.sock – if so, the smtpd_milters line above should be changed to:

smtpd_milters = unix:/spamass/spamass.sock, inet:localhost:12345

Create the TrustedHosts, KeyTable and SigningTable files as follows (substitute your domain(s) for in all of them)



Substitute the second block of IP addresses with real addresses from your server – don’t leave the Google DNS addresses there! Note that the /64 at the end of the IPV6 address is required.


Note multiple domain substitutions; DKIM also uses ‘selectors’ which are defined here. I’ve used “mail” as the selector (some folk will recommend something like “jan2016”), but you can use whatever you’d like:

/etc/opendkim/SigningTable (again with the multiple domain substitutions):


You’ll notice that the KeyTable file mentions a directory for your domain – create that now:

sudo mkdir /etc/opendkim/keys/

In the directory you just created, create the private/public key pair (note another domain substitution, and if you changed the selector above from “mail” to something else, you’ll need to change it here too):

sudo opendkim-genkey -b 2048 -s mail -d

Change the owner of the private key:

sudo chown opendkim:opendkim mail.private

The mail.txt file contains the TXT record you need to add to your DNS. Note that the key is broken up in to multiple quoted sections – be careful when adding it to your DNS records to make sure it’s all added correctly.

Wait until the DNS change has propagated, then confirm that the DKIM key in your DNS records passes a validation check. If everything looks good, restart the opendkim and postfix processes:

sudo systemctl restart opendkim
sudo systemctl restart postfix

Send a test email to a Gmail account. Here’s what you should see in the mail logs for the outbound message:

opendkim[11862]: D11F114939: DKIM-Signature field added (s=mail,

In Gmail, when the test email arrives, it should have the following headers:

       spf=pass ( domain of designates [IP Address] as permitted sender);
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple;; s=mail;

Reply back to the email and check the mail logs for the following:

opendkim[11862]: 0EBC014939: [2607:f8b0:4003:c01::235] not internal
opendkim[11862]: 0EBC014939: not authenticated
opendkim[11862]: 0EBC014939: DKIM verification successful
opendkim[11862]: 0EBC014939: s=20120113 SSL

If you have SpamAssassin installed, you should also see something like the following:

spamd[18803]: spamd: result: . 0 - DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,FREEMAIL_FROM,HTML_MESSAGE,SPF_PASS,UNPARSEABLE_RELAY scantime=0.4,size=2698,user=user,uid=5000,required_score=5.0,rhost=::1,raddr=::1,rport=52616,mid=<>,autolearn=ham autolearn_force=no

Another test you can (and should) run is the Newsletters spam test, as it will make sure your mail is correctly signed using DKIM.

Once you are absolutely certain that both SPF and DKIM are working correctly…

Outbound DMARC

Similar to outbound SPF, outbound DMARC is set up as a DNS TXT record that defines how receiving mail servers should handle messages that fail SPF and DKIM checks. DMARC is only useful if SPF and DKIM are working for your domain, AND if all outbound mail for your domain goes through your servers.

If other servers are used (e.g., using an ISP mail server as a smarthost), then do not configure a DMARC record!

I really like Google’s guide for Preventing outgoing spam with DMARC and consider it mandatory reading.

Google’s guide will help you configure your own DMARC record, but as an example – here’s mine: IN TXT "v=DMARC1; p=quarantine; pct=100;"

Inbound DMARC

Install the following:

sudo aptitude install opendmarc

My /etc/opendmarc.conf – I’ve chosen to not send forensic/aggregate reports and to not reject mail that fails DMARC (for the time being):

AutoRestart             Yes
AutoRestartRate         10/1h

UserID                  opendmarc:opendmarc
Socket                  inet:54321@localhost
Syslog                  true
SyslogFacility          mail

AuthservID              mail.server.fqdn
#TrustedAuthservIDs      other.mail.server, another.mail.server
IgnoreHosts             /etc/opendkim/TrustedHosts

RejectFailures          false

Uncomment the TrustedAuthservIDs if you have additional mail server(s) configured for the same domain(s) that also have OpenDMARC installed.

Next, configure the socket by adding the following line to /etc/default/opendmarc (don’t uncomment anything):


Add to the list of milters in /etc/postfix/

smtpd_milters = unix:/spamass/spamass.sock, inet:localhost:12345, inet:localhost:54321

Start and restart the appropriate processes:

sudo systemctl start opendmarc
sudo systemctl restart postfix

Send yet another test email from Gmail and then look for the following in the mail logs:

opendmarc[23774]: E24C514939: pass

You’ll also see the following in the mail header:

Authentication-Results: mail.server.fqdn; dmarc=pass