https://iliasa.eu/blog/feed.xml

Postfix: Discard mail based on header

2021-07-21

This post will help you keep your mailbox clean if you are hit by a constant spammer and you want to discard the message completely. Not just move it to your spam folder.

Prerequisites

Postfix with PCRE support

root@server:~# postconf -m | grep pcre
pcre

Configuration

Edit /etc/postfix/main.cf

We will use the header_checks = parameter to load the file that will hold the info of the spammer.

Append header_checks = pcre:/etc/postfix/header_checks to your main.cf file.

vim /etc/postfix/main.cf
.
.
.
header_checks = pcre:/etc/postfix/header_checks

Edit /etc/postfix/header_checks

Now, let's create the header_checks file.

vim /etc/postfix/header_checks

In my case, I wanted to block the 'Предложение' subject.

Note that because this Subject: header is UTF8 encoded and postfix checks the raw header, I had to use the UTF8 encoded equivalent: /=?utf-8?B?0J/RgNC10LTQu9C+0LbQtdC90LjQtQ==?=/.

I found the raw version by checking the source of the mail (with Thunderbird) which contains the headers in raw format.

The general format of header_checks file is:

/Regular Expression/ ACTION

In this particular case:

/=\?utf-8\?B\?0J\/RgNC10LTQu9C\+0LbQtdC90LjQtQ==\?=/ DISCARD

Note: Had to escape some characters, as you see.

You can find more about actions here.

Now, let's finalize the header_checks file with postmap:

root@server:~# postmap /etc/postfix/header_checks 

Restart postfix

root@server:~# systemctl restart postfix

Conclusion

Jul 21 10:24:07 server postfix/cleanup[12095]: A1DEFB52C1: discard: header Subject: =?UTF-8?B?0J/RgNC10LTQu9C+0LbQtdC90LjQtQ==?= from XXXXX; from=<XXXXX> to=<XXXXX> proto=ESMTP helo=<XXXXX>