Stop Spam Through Postfix on CentOS: A Step-by-Step Guide
In this article
This guide walks you through the practical steps to reduce spam on a CentOS-style server running Postfix. You'll learn how to configure Postfix to reject obvious spam, use DNS-based blacklists (DNSBLs), enforce sender restrictions, and add SPF, DKIM, and DMARC checks. By the end, you'll have a significantly hardened mail server that blocks a large portion of incoming spam before it reaches your users' inboxes.
What You'll Need
- Root or sudo access to your CentOS server (7, 8, or 9; or Rocky/AlmaLinux).
- Postfix already installed and running (check with
systemctl status postfix). - Basic familiarity with the command line and editing files with
viornano. - A domain name that you control, if you plan to set up SPF, DKIM, and DMARC (recommended).
Step-by-Step
- Back up your current Postfix configuration.
Before making changes, copy the main configuration file so you can revert if needed:
cp /etc/postfix/main.cf /etc/postfix/main.cf.bak - Enable basic spam rejection in
main.cf.
Edit/etc/postfix/main.cfand add or modify these parameters. They reject mail that is obviously malformed or from invalid senders.
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_non_fqdn_sender, reject_non_fqdn_recipient, reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permitThis list is processed in order. The first three lines allow mail from your own network and authenticated users, and ensure you're not an open relay. The rest reject mail with invalid HELO names, non-FQDN sender/recipient, unknown domains, and IPs listed in Spamhaus and SpamCop. - Add SPF (Sender Policy Framework) checks.
Install the Postfix SPF policy agent:
yum install postfix-pcre postfix-perl-scripts(on CentOS 7) ordnf install postfix-pcre postfix-perl-scripts(on CentOS 8/9).
Then, inmain.cf, add:
policyd-spf_time_limit = 3600 smtpd_recipient_restrictions = ... (your existing list) ... check_policy_service unix:private/policyd-spfNow configure the policy agent by editing/etc/postfix/policyd-spf.confand setting:
SPF_ACTION = reject(orpermissiveto just add a header). - Set up DKIM (DomainKeys Identified Mail) with OpenDKIM.
Install and configure OpenDKIM:
yum install opendkim(ordnf).
Edit/etc/opendkim.confto set:
Mode sv Canonicalization relaxed/simple Socket inet:8891@localhost SigningTable refile:/etc/opendkim/signing.table KeyTable refile:/etc/opendkim/key.table
Generate a key for your domain (e.g., forexample.com):
opendkim-genkey -s mail -d example.com -D /etc/opendkim/keys
Then create thesigning.tableandkey.tablefiles with the appropriate mappings. Finally, add tomain.cf:
milter_default_action = accept milter_protocol = 6 smtpd_milters = inet:localhost:8891 non_smtpd_milters = inet:localhost:8891
Start and enable OpenDKIM:systemctl enable --now opendkim. - Add DMARC (Domain-based Message Authentication, Reporting & Conformance) checks.
DMARC is a DNS record that tells receiving servers what to do with mail that fails SPF and DKIM. Add a TXT record for_dmarc.example.comin your DNS:
v=DMARC1; p=quarantine; rua=mailto:dmarc@example.com
Start withp=noneto monitor, then tighten toquarantineorrejectonce you're confident your legitimate mail passes. - Enable greylisting (optional but effective).
Greylisting temporarily rejects mail from unknown senders, forcing spammers to retry (which they often don't). Install postgrey:
yum install postgrey(ordnf).
Add tomain.cf:
smtpd_recipient_restrictions = ... (your list) ... check_policy_service inet:127.0.0.1:10023Start and enable postgrey:systemctl enable --now postgrey. - Restrict HELO and sender domain checks.
Inmain.cf, add these to your restrictions to block mail with suspicious HELO names or sender domains that don't resolve:
reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_sender_domain,
(These are already in the list from step 2, but ensure they are present.) - Set limits on message size and connections (optional).
Add tomain.cfto reduce abuse:
message_size_limit = 10240000 smtpd_client_connection_rate_limit = 10 smtpd_client_message_rate_limit = 20
Adjust numbers to your needs. - Restart Postfix and test.
After all changes, runpostfix checkto validate the config, then restart:
systemctl restart postfix
Send a test email from an external account to ensure it arrives. Check the mail logs withtail -f /var/log/maillogto see if any legitimate mail is being rejected.
Common Mistakes
- Overly strict restrictions: Blocking too much can reject legitimate mail from servers with poor DNS or dynamic IPs. Test with a monitoring service or send test emails from various providers.
- Missing SPF/DKIM records: If you enable SPF checks but don't publish SPF records for your own domain, your outgoing mail may be flagged. Ensure your DNS records are correct.
- Incorrect milter configuration: If OpenDKIM is not listening on the correct socket, Postfix may fail to start. Double-check the
Socketline inopendkim.confand thesmtpd_miltersline inmain.cf. - Forgetting to open firewall ports: If you run a firewall, ensure ports 25, 465, and 587 are open for incoming mail.
- Not backing up before changes: Always keep a backup of
main.cfbefore editing, so you can revert quickly.
Tips
- Start with
reject_rbl_clientin a non-fatal mode (e.g.,warn_if_reject reject_rbl_client) to see how many legitimate mails are blocked before enforcing it. - Use a monitoring tool like
pflogsummto review mail logs and identify false positives. - Regularly update your DNSBL lists; Spamhaus and SpamCop are free but have usage limits. Consider using a commercial service if you have high volume.
- Implement SPF, DKIM, and DMARC on your own domain to improve deliverability and reduce the chance of your domain being spoofed.
- Consider using a content filter like SpamAssassin in addition to the above, for deeper analysis.
Troubleshooting
- Postfix fails to start: Run
postfix checkto see syntax errors. Look at/var/log/maillogfor specific error messages. Common issues: missing closing parentheses in restrictions, or a milter socket that isn't available. - Legitimate mail is being rejected: Check the maillog for the reason. If it's due to an RBL, remove that RBL or use
warn_if_rejecttemporarily. If it's due to SPF, your SPF record might be too strict (e.g.,-allinstead of~all). - Outgoing mail is marked as spam: Verify your SPF, DKIM, and DMARC records are correctly published. Use online tools to check them. Ensure your server's IP is not blacklisted.
- Greylisting delays mail: Some legitimate senders don't retry quickly. You can whitelist known senders in postgrey's whitelist file, or reduce the delay time.
- OpenDKIM not signing: Check that the key files are readable by the opendkim user, and that the signing table paths are correct. Test with
opendkim-testkey.
Frequently Asked Questions
Will these steps block all spam?
No. They block a significant portion (often 80-90%) of obvious spam, but some will still get through. Combining with a content filter like SpamAssassin is recommended for higher accuracy.
Do I need to set up SPF, DKIM, and DMARC?
Yes, if you want to prevent your domain from being spoofed and improve your outgoing deliverability. They also help receiving servers trust your mail, which reduces the chance of your legitimate mail being flagged as spam.
What is the difference between reject_rbl_client and reject_unknown_sender_domain?
reject_rbl_client checks the connecting IP against a DNS blacklist. reject_unknown_sender_domain rejects mail from a sender whose domain doesn't have a valid DNS MX or A record. Both are useful.
Can I use these settings on a non-CentOS server?
Yes, the Postfix configuration is largely distribution-agnostic. The package names and service commands may differ (e.g., using apt on Debian/Ubuntu), but the main.cf parameters are the same.
How do I test if my configuration is working?
Send a test email from a free webmail service (like Gmail) to your server. Check the headers for SPF, DKIM, and DMARC results. Also, you can use online tools like mail-tester.com to get a score and see what's wrong.
What if I need to allow a specific sender that is being blocked?
You can add a whitelist rule in smtpd_recipient_restrictions before the reject rules. For example, check_client_access hash:/etc/postfix/client_whitelist and then list the IP or domain in that file with OK.