I write this article because it was really hartd to find anything useful for this problem.
I wanted to add an [External]-String to the subject for all incoming external mails in our postfix relay server which is also filtering spam. While this is pretty simple if you want to do it with every incoming mail by using smtp_header_checks, it gets ugly if you want to exclude some mail addresses from this rule. I first tried to do it with transport rules but didn’t like the complexity of configuration over several files. Another idea was to use alterMIME. Since its development is stuck for over a decade now, I decided against it.
After a lot of searching I found a thread in the german debianforum which described a solution based on mimedefang. Its integration in postfix is based on milters. So it is easy to use. I will show how to use it on a ubuntu machine
Now lets start with the howto
First install mimedefang
apt install mimedefang
then enable a tcp-listener socket in /etc/default/mimedefang by adding the following line to the file
SOCKET=inet:17889
Now you have to create the a script file in perl what actualy does the rewriting. This sample taken from the forum thread only rewrites mail for a specific domain. It can be easily modified to do specifc rewrites
It has to have the following name: /etc/mail/mimedefang-filter
# -*- Perl -*-
# -- values from the template
$AdminAddress = 'postmaster@localhost';
$DaemonAddress = 'mailer-daemon@localhost';
$Stupidity{"NoMultipleInlines"} = 0;
# ---------------------------
sub filter_end {
my($entity) = @_;
for ($count=0;$myRecipient=$entity->head->get("To",$count);$count++) {
if($myRecipient =~ m/\<[^@]+\@mydomain.com\>/) {
$sbj = $entity->head->get("Subject",0);
action_change_header("Subject","[External] $sbj");
break;
}
}
}
# DO NOT delete the next line, or Perl will complain.
1;
Now the mimedefang service hase to be enabled and started
systemctl enable mimedefang.service
systemctl start mimedefang.service
For postfix to use mimedefang simply add it to you milter in postfix main.cf
# if mimedefang is the only milter
smtpd_milters = inet:localhost:17889
# rspamd + mimedefang
smtpd_milters = inet:localhost:11332, inet:localhost:17889
then restart postfix and you are good to go.
systemctl start postfix.service
If you make any modifications to the filterscript you have to restart mimedefang.
If anything is unclear please add a comment and I try to write a more detailed version