Skip to main content

Gmail-style Aliasing with Postfix

One of Gmail’s lesser-known features is plus addressing: e-mail sent to an alias of your main address, such as john.doe+22@gmail.com, is delivered to the main mailbox, john.doe@gmail.com, where it can be labeled and placed in different folders. (Note: this address is made up, and hopefully it doesn’t belong to a real person.)

How could you reproduce this on a mail server you run yourself? I won’t go into every detail, just scratch the surface. With Postfix (the default MTA on Red Hat, Fedora and CentOS), the place to start is the virtual_alias_maps option in the configuration file, main.cf.

Maps are a core concept throughout Postfix’s configuration. A map translates an input (for example, an e-mail address) into a desired output (for example, a mailbox location on disk or the real destination address). Postfix treats “virtual” as anything not tied to a real Unix account. To get Gmail-style aliasing, you therefore need a virtual map that converts addresses containing a + into the main mailbox address.

Since the aliased addresses can’t be predicted in advance, the only way to match them to the real destination is with some kind of regular expression matching. Simple Postfix map types, such as hash tables, only do exact matching, so you could alias john.doe+1 to john.doe, but that wouldn’t cover john.doe+2 or john.doe+99, unless you added a separate line for each possible alias.

The better news is that Postfix can match regular expressions through the corresponding built-in module, so the configuration could look like this:

# cat /etc/postfix/main.cf | grep virtual_alias_maps

virtual_alias_maps = regexp:/etc/postfix/virtual_alias

The virtual_alias file could then contain:

# cat /etc/postfix/virtual_alias

/^sample.name+(.*)@brainware.ro$/	sample.name@brainware.ro

This works, but it has some drawbacks:

  • Manual maintenance. You have to edit the virtual_alias file by hand to add new aliases. That isn’t practical for large installations where accounts are created and removed through web interfaces.
  • Performance. Postfix itself performs the regex matching, which can in theory reduce mail throughput. On a busy server with thousands of such aliases this might become noticeable, though it’s probably not a serious problem on modern hardware.

The fix for both issues is to hand the address matching over to a database such as MySQL or PostgreSQL and do the regex matching in a stored procedure. I may return to this in a later post, but for now, thanks for reading!