How to Configure Postfix for Wildcard Subdomain Email Handling with Pipe Delivery


8 views

When implementing wildcard subdomain email handling in Postfix, we need to address two key technical aspects:

  • Proper domain matching configuration in main.cf
  • Correct pipe delivery setup for processing scripts

Instead of listing all possible subdomains, use transport_maps combined with regex matching:

# In main.cf
mydestination = $myhostname, localhost.$mydomain, localhost
virtual_alias_domains = regex:/etc/postfix/virtual_domains
virtual_alias_maps = regex:/etc/postfix/virtual_aliases

Create /etc/postfix/virtual_domains:

# Match any subdomain of mydomain.com
/^[^.]+\.mydomain\.com$/ OK

Configure /etc/postfix/virtual_aliases:

# Route all python@subdomain.mydomain.com to your script
/^python@[^.]+\.mydomain\.com$/ python

Then define the transport in /etc/postfix/transport:

python unix - - n - - pipe
  flags=Rq user=python argv=/www/proc_email.py
  ${nexthop} ${user}

Ensure your proc_email.py script:

  1. Has proper execute permissions
  2. Handles stdin for email content
  3. Includes proper shebang (#!/usr/bin/env python)
  4. Processes email headers correctly

Use these Postfix commands to verify your setup:

postmap /etc/postfix/virtual_domains
postmap /etc/postfix/virtual_aliases
postmap /etc/postfix/transport
postfix reload

Check logs with:

tail -f /var/log/mail.log

For more complex scenarios, you might modify your Python script to extract the subdomain:

import sys
import email
from email.header import decode_header

msg = email.message_from_file(sys.stdin)
to_header = msg['to']
# Extract subdomain from to address
# Process message based on subdomain

When setting up a mail server that needs to handle emails for dynamic subdomains (like *.mydomain.com), Postfix's default configuration requires explicit domain listing. Here's how to make it work with wildcards while piping emails to Python scripts.

First, check your Postfix version:

postconf mail_version

The key configuration file is /etc/postfix/main.cf. Here's the crucial setting:

mydestination = $myhostname, localhost.$mydomain, localhost, *.mydomain.com

For proper wildcard handling, you'll need:

# In main.cf
virtual_alias_domains = mydomain.com
virtual_alias_maps = hash:/etc/postfix/virtual

Then in /etc/postfix/virtual:

@.mydomain.com    python

The alias definition for piping to your Python script:

# In /etc/aliases
python: "|/www/proc_email.py"

Remember to update aliases:

newaliases
systemctl reload postfix

Check if Postfix recognizes your domain:

postmap -q mydomain.com virtual_alias_domains

View mail queue:

mailq

Test SMTP reception:

telnet localhost 25
EHLO test.com
MAIL FROM:<test@example.com>
RCPT TO:<python@anything.mydomain.com>

For more complex subdomain patterns:

# In main.cf
virtual_alias_maps = pcre:/etc/postfix/virtual_regexp

Then create regex patterns:

/^python@.*\.mydomain\.com$/  python