Postfix Backup MX eMail Server Anti-Spam Configuration

According to RFC2821 the lowest-numbered records are the most preferred MX for domain. So I’ve a target Postfix backup server to keep the messages in a queue waiting for the primary server to become available. This ensures that if my primary MX goes down I do not loss any emails. However, spammers are connecting to my backup MX to avoid anti spam filters that are running on the primary MX server. This also hides their real IP from my primary MX. How do I configure anti-spam for my backup RHEL / CentOS 5.3 based Postfix mx server?

This is well known issue. Make sure your backup MX runs the same config in terms of spam rejection as your primary server. Try the following to improve backup eMail server anti spam configuration.

If the backup MX acts as a store-and-forward mail server

Consider the following example:	86400	IN	MX 	10	86400	IN 	MX 	20 email handled by two email servers. is your backup server. Open and append the following restrictions on

Only allow your own domain to accept email

Use relay_domains to relay email for two domain called and Also, set lookup tables with all valid addresses in the domains that match $relay_domains i.e. only accept email for valid email address.
# vi /etc/postfix/
Modify settings as follows:

relay_domains =,, $mydestination
relay_recipient_maps = hash:/etc/postfix/relay_recipients

Create /etc/postfix/relay_recipients to accept email for,, and so on..   OK   OK    OK

Save and close the file. Finally, update your db:
# postmap hash:/etc/postfix/relay_recipients

Anti spam via RBL

Now, add following lines to check spammer IP address using RBLs. Reject all email if they do not have a valid hostname or proper email address:

smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks,
# helo required 
smtpd_helo_required = yes
# disable vrfy command 
disable_vrfy_command = yes

smtpd_data_restrictions =

Save and close the file. Restart / reload postfix:
# service postfix reload
There are other anti UCE settings, see Postfix anti UCE cheat sheet for more information.

Nolisting mx A entry

Spammers email software does not retry higher-priority MX records. So all you have to do is create a non-existent primary mail server and a working secondary mail server, attempts to contact the primary mail server will always fail. This technique uses a non-existent primary mail server, which is compatible with all correctly configured mail servers such as Sendmail, MS-Exchange, Postfix, Qmail, Exim etc. Create BIND dns configuration as follows:	86400	IN	MX 	10	86400	IN 	MX 	20	86400	IN 	MX 	30	86400	IN 	MX 	40


  • – Runs your actual primary MX with anti spam and anti virus configurations.
  • – Your backup mx server with anti spam / virus and act as store and forward server for
  • and are nolist MX servers. They can either be dead (or point to non existing IP) or you can run SMTP on port 25 that always returns 4xx error so that legitimate MTA to retry on a lower numbered MX server. nolist MX servers can also used to get more information about spammers to blacklist them. Google for “spam filtering services that offer free nolist servers” specifically for botnet data harvesting.

Greylisting Backup MX

Postfix can be configured to temporarily reject any email from a sender it does not recognize. If the mail is legitimate, the originating server will try again and the email is accepted. If the mail is from a spammer it will probably not be retried since a spammer goes through thousands of email addresses and cannot afford the time delay to retry. See how to configure postfix greylist policy server.

Spamassassin+Amavis+Clamd For Backup MX Server

Spamassassin is open source mail filter, to identify spam using a wide range of heuristic tests on mail headers and body text. You can install Spamassassin spam checking on your backup server. Emails found to be Spam (with higher spam score) will be drop out before reaching your primary email server. You can also use Clamav / Amavis to scan email and drop or forward infected emails. Install spamassassin, clamd and amavisd-new using yum or apt-get commands (turn on EPEL repo under RHEL / CentOS to install the following packages):
# yum install clamav-server amavisd-new spamassassin

  • clamav-server : Clam Antivirus scanner server
  • amavisd-new : amavisd-new is a high-performance and reliable interface between Postfix and virus scanners, and/or
    Mail::SpamAssassin Perl module.
  • spamassassin : Spam filter for email which can be invoked from mail delivery agents or in our case via amavisd-new

Once done, add as the following to your /etc/postfix/


Save and close the file. Open /etc/postfix/ and add the following settings:

smtp-amavis unix - - n - 2 smtp
  -o smtp_data_done_timeout=2400
  -o smtp_send_xforward_command=yes
  -o disable_dns_lookups=yes
  -o max_use=20 inet n - n - - smtpd
  -o content_filter=
  -o local_recipient_maps=
  -o relay_recipient_maps=
  -o smtpd_restriction_classes=
  -o smtpd_delay_reject=no
  -o smtpd_client_restrictions=permit_mynetworks,reject
  -o smtpd_helo_restrictions=
  -o smtpd_sender_restrictions=
  -o smtpd_recipient_restrictions=permit_mynetworks,reject
  -o mynetworks_style=host
  -o mynetworks=
  -o strict_rfc821_envelopes=yes
  -o smtpd_error_sleep_time=0
  -o smtpd_soft_error_limit=1001
  -o smtpd_hard_error_limit=1000
  -o smtpd_client_connection_count_limit=0
  -o smtpd_client_connection_rate_limit=0
  -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_address_mappings

Save and close the file. Also, update /etc/amavisd/amavisd.conf with required settings.

$daemon_user  = 'amavis';     # (no default;  customary: vscan or amavis), -u
$daemon_group = 'amavis';     # (no default;  customary: vscan or amavis), -g
$mydomain = '';   # a convenient default for other settings
$log_level = 1;              # verbosity 0..5, -d
$DO_SYSLOG = 1;              # log via syslogd (preferred
$inet_socket_port = 10024;   # listen on this local TCP port(s) (see $protocol)
$sa_tag_level_deflt  = -999;  # add spam info headers if at, or above that level
$sa_tag2_level_deflt = 6.31; # add 'spam detected' headers at that level
$sa_kill_level_deflt = 6.31; # triggers spam evasive actions
$sa_dsn_cutoff_level = 10;   # spam level beyond which a DSN is not sent
$virus_admin               = 'postmaster\';                    # notifications recip.
$mailfrom_notify_admin     = 'postmaster\';                    # notifications sender
$mailfrom_notify_recip     = 'postmaster\';                    # notifications sender
$mailfrom_notify_spamadmin = 'postmaster\';                    # notifications sender
$mailfrom_to_quarantine = 'postmaster\'; # null return path; uses original sender if undef
$sa_spam_subject_tag = '***SPAM*** ';
$myhostname = '';  # must be a fully-qualified domain name!
$notify_method  = 'smtp:[]:10025';
$forward_method = 'smtp:[]:10025';  # set to undef with milter!
# add your server public ip, private ip, 
@inet_acl = qw( 127/8;

Save and close the file. Update spamassassin settings in /var/spool/amavisd/:
# usermod -s /bin/bash amavis
# passwd amavis
# su - amavis
$ razor-admin -discover
$ razor-admin -create
$ razor-admin -register -l -pass=somePassword
$ cd .spamassassin
$ cp /usr/share/spamassassin/user_prefs.template user_prefs
$ exit
# usermod -s /sbin/nologin amavis

Update /etc/clamd.d/amavisd.conf as follows:

# Use system logger.
LogSyslog yes

# Specify the type of syslog messages - please refer to 'man syslog'
# for facility names.
LogFacility LOG_MAIL

# This option allows you to save a process identifier of the listening
# daemon (main thread).
PidFile /var/run/amavisd/

# Remove stale socket after unclean shutdown.
# Default: disabled
FixStaleSocket yes

# Run as a selected user (clamd must be started by root).
User amavis

# Path to a local socket file the daemon will listen on.
LocalSocket /var/spool/amavisd/clamd.sock

Update /etc/mail/spamassassin/ as follows:

required_hits 6.31
report_safe 1
rewrite_subject         0
# Enable the Bayes system
use_bayes               1
# Enable Bayes auto-learning
auto_learn              1

Save and close the file. Finally, restart postfix and other services:
# service clamd.amavisd start
# service amavisd start
# service postfix restart

Turn services on boot:
# chkconfig clamd.amavisd on
# chkconfig amavisd on
# chkconfig postfix on

Now, check your /var/log/maillog for any errors or details:
# netstat -tulpn -A inet| egrep ':25|:1002?'
# tail -f /var/log/maillog

Above configuration will open the following ports on server:

  1. 10024 – Amavisd
  2. 10025 – Amavisd will communicate back the results to Postfix
  3. 25 – SMTP Port

A note about same priority mx servers

You can point the mail servers, all with the same priority. It offers the following benfits:

  • Load balancing
  • Centralized user mail managment via LDAP or MySQL / PGSQL
  • Centralized virus scanning
  • Centralized Spam scanning

Sample dns records:	86400	IN	MX 	10	86400	IN 	MX 	10	86400	IN 	MX 	10
; imap server
imap		86400	IN 	A
; pop3 server - can be CNAME too
pop3		86400	IN 	A

You may need additional servers inside your lan:

  • MySQL/OpenLDAP ( – Store user name, email, mailbox and other information.
  • Central anti virus server ( – Used by all your mx servers for scanning using TCP/IP. You can also do the same for spam scanning using TCP/IP.

Each mx server can use centralized anti spam and anti-virus server. Once scanned Postfix can deliver final mail which can be retrieved using POP3 / IMAP server.

Further Readings / References :

This FAQ assumed that you have working Postfix primary and backup server. It only covered anti spam related topics. For further details refer the following urls and respective man pages:

šŸ§ Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

šŸ§ 14 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
14 comments… add one
  • Aaron Apr 28, 2009 @ 22:59

    This all sounds well and good–but the problem is that Spammers will adapt. They will figure out the MX priority tricks and modify their software. They already know a lot about greylisting and try again 5-15 minutes later.

    The real solution is to keep your list of postfix users and domains in a file or database that gets synced every few minutes, hours, or days–whatever is appropriate. That way both servers know the correct list of domains and users for forwarding.

    I personally just trigger the sync by hand now–but in the past I’ve used rsync and a cron job.

    • šŸ§ nixCraft Apr 29, 2009 @ 0:25

      I belive relay-domains and and relay_recipient_maps does the same thing. You can use MySQL database and just run in master – slave mode.


  • qBert Apr 29, 2009 @ 6:43


    the “reject_unverified_recipient” Option on the backup mx could be usefull too:

  • Jack Apr 30, 2009 @ 0:13

    Yeah, it’s like Aaron said, spammers are great at adapting to the anti-spam measures and always seem to find a way through.
    -Jack @ mac backup software

  • Gokdeniz Karadag Apr 30, 2009 @ 19:44

    While backup MX seems like a good idea, in practice you can do without them.

    All mail software retry sending mail for a reasonable amount of time. Postfix retries for FIVE DAYS. Let’s be on the safe side and let’s say all mail servers try delivery for at least two days.

    When a problem occurs, you will most likely solve it in two days. If you cannot, you can restore your backed up configuration in a new server as a last resort. It is a very unlikely scenario that a mail server cannot be fixed or replaced within two days.

    So, instead of trying to fortify the backup server, and trying to keep the setings in sync, you can have only one server and focus on it.

    If you have a very high mail volume and need load balancing, then you probably sync all configurations and use a central spam filter; so keeping a backup may not be expensive. But for all other cases where a single server is powerful enough to handle mail, I strongly recommend keeping only one server up. I have only one server in our 2000 user environment, for about 3 years, and did not have any problem.

    But I have to admit we have a good backup policy and scripts ready to build a server from scratch, so I am confident about overcoming outages.

    • šŸ§ nixCraft Apr 30, 2009 @ 20:23

      It will take at least 2-3 hrs to create (replace hardware, os reloads, patch and data) and restore data from a backup server / tape. What will happen if someone try to send emails to those 2000 users? Some free services such as Yahoo / Gmail and Exchange server gives up immediately and returns email to sender. This may be good for a small business or non-profit organizations but for any serious business you need to have backup mx server.


  • Gokdeniz Karadag Apr 30, 2009 @ 20:55


    RFC 2821 requires that mailing software MUST retry sending mail after failed attemps See section 4.5.4 at

    A quick test with both gmail and yahoo showed that it does not immediately give up.

    I cannot currently test with exchange server, but if it gived up immediately, it cannot deliver mailt to all those servers using “nolisting”. As nolisting simulates a broken MX.

    • šŸ§ nixCraft Apr 30, 2009 @ 21:08


      My bad – I misread your first post… yes, each server including those run by Google / Yahoo are actually configured to hold mail for a few days. Also, Exchange try out next server immediately if primary is down. Most nix based server wait for some time. But, in general all of them retry delivery.

      PS: swaks is wonderful tool for testing various email configurations!

  • Greg Jul 21, 2009 @ 15:40

    I’ve been using a backup MX with postgrey for years now and it works a treat !
    However Ihave often wondered what if I cant fix/replace the primary server within a few days, sure my backup keeps queuing for 60 days meanwhile my clients have no access, not good.
    I already backup my IMAP Maildirs to the backup MX and user accounts are also working there with LDAP replicated auth to boot.
    How do I tell postfix on the backup MX to stop queuing and deliver all the mail it has queued locally ?

  • Aaron Jul 21, 2009 @ 15:48

    Greg: Keep a backup copy of your primary MX config somewhere on the backup MX. When the primary MX goes down for good, stop postfix, copy the backup of the primary MX config into the correct location and start postfix (make sure your maildirs are in place too).

    If Postfix doesn’t deliver the messages, try “postsuper -r ALL’
    The -r is for ‘requeue’. It pretty much takes every queued message and moves it into the maildrop for reprocessing. It should recognize that the message is now destined for a local mailbox and deliver it accordingly.

  • Seth Wisely Oct 27, 2009 @ 22:47

    No mention of redundant DNS? Backup MX is fine but with resolver failure even backup MX can be useless.

    A more interesting idea (rough draft imagination) would be a symlink-analog from backup (third party) MX providers to access rules on primary (or local MX) such that rules need not be manually replicated.

    While some find it rude I find TMDA efficacious (when properly configured)

  • Acorp Oct 19, 2010 @ 6:07

    Just wanted to say the NOLIST MX Servers trick is awesome! SPAM messages hitting my server dropped nearly 90% after implementing a lowest priority nolist MX server and a highest priority nolist MX server. Some statistics from my mail server are listed below. One caution…I’ve heard that QMAIL may not respond correctly to a 4xx NOLIST server, so it may be best to use a non-existent/invalid IP for your nolist servers. YMMV…

    10/14/2010: 42517 Messages Rejected
    10/15/2010: 40604 Messages Rejected
    10/16/2010: 22801 Messages Rejected
    NOLIST MX Server records created early afternoon 10/17
    10/17/2010: 7580 Messages Rejected
    10/18/2010: 3320 Messages Rejected

  • Mikaso Nov 27, 2011 @ 5:13

    gpasswd -a clam amavis

  • Westlife Jun 12, 2012 @ 2:57

    Dear, Can I creat three mx server for receive messages? After this servers send to main server.
    Iā€™d like to creater a cluster of mx server just to receive mail (filter virus, spam ) after that send to primary where exist useres. It is possible?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum