Latest News & Blog

Postfix limit mail to predefined IPs for specific domains

Monday 20 February, 2023

HOWTO: Accepting email from only a predefined whitelist of IPs for specific domains in Postfix.


Imagine that  you have a postfix email server which is the MX record and SMTP delivery endpoint for a number of domains. This domain is getting more spam than you would like so you choose to place it behind an email filtering service. However, only this domain, not all.  The MX records for those few domains may be moved to point at the spam-filter service but your server is still the end delivery point as the emails are being smtp relayed to it from the mail-fitler service.  Well, if a spammer knew about this end point (which they most likely do if your moving a domain due to spam levels), then they could bypass the mailfilter and continue to deliver email directly to your server.

The solution

This solution sets postfix to only accept email from a predefined whitelist of IP addresses and only for specific domains. For the usecase above, this would mean for the domains you moved, you could set the that email should only be accepted from the IP addresses of the spam-filtering service.


1) Create the file with the IP addresses you wish to whitelist. This should be a file with one per line, in CIDR notation.

The last line of this file should have a catch all set to reject.

e.g. If you was using cloudflare's mail filtering service, this would be;

nano -w /etc/postfix/mf_ips


This file does not need a hashmap


2) Create a file with the domains you wish to protect as a postfix  hashmap

nano -w /etc/postfix/mf_domains

Contents of which are; mf mf mf

Create the postfix hash map of the above file

postmap /etc/postfix/mf_domains


3) Update postfix

Add the following lines;

smtpd_restriction_classes = mf
mf =  check_client_access cidr:/etc/postfix/mf_ips, permit

Into your existing smtpd_recipient_restrictions section, add the following line;

check_recipient_access hash:/etc/postfix/mf_domains,

e.g. - The resulting smtpd_recipient_restrictions section may look like this;

smtpd_recipient_restrictions =
       check_recipient_access        hash:/etc/postfix/mf_domains,


4) Now reload postfix  ---  you're all set.



Hopefully this howto has been helpful.

If you would prefer an experienced pair of hands perform this for you -- or if you just require assistance with your Linux servers, Postfix or spam filtering then Leenix are here to help. 

We provide consultancy services for exactly these sorts of problems and pride ourselves on our customer focused Linux problem solving and solution specification.


Written By...

Lee Simpson

Software Engineer, Linux Wizard, proud father of 3 boys