A Mailserver in Ubuntu 12.04: Postfix, Dovecot, MySQL

From Wiki - UNIXSOL LTD

Jump to: navigation, search

Contents

Requirements

Fresh minimal Ubuntu 12.04 installation

Basic setup

The baseline Ubuntu instance is lacking in near every package you might need, so you are building from fairly close to scratch. You'll log in as the "ubuntu" user and then switch to root; most of what you need to do requires root access:

sudo su

You must set up a permanent IP address. By default, an Ubuntu installation will have its own hostname, so changing to the domain the server will have is the first item on the list:

hostname mail.example.com

Now set the contents of /etc/hostname to be the hostname:

mail.example.com

And add your hostname to the first line of /etc/hosts:

 127.0.0.1 mail.example.com localhost
 
 # Usually some IPv6 configuration below the first line, but leave that alone.
 ...

Now you'll want to regenerate the server's default self-signed SSL certificate so that it matches the domain name. You may have purchased an SSL certificate for your mail server, but it is perfectly possible and completely secure to run a mail server using a self-signed certificate. The only consequences will be warning screens when using webmail hosted on the server and warnings from Microsoft Outlook when connecting via POP, IMAP, or SMTP.

apt-get install ssl-cert
make-ssl-cert generate-default-snakeoil --force-overwrite

Build a LAMP Web Server

You will need the mailserver to also be a LAMP (Linux, Apache, MySQL, PHP) web server, since you will want webmail and a web-based administrative interface for managing users. So turning your Ubuntu instance into a web server is a good place to start. There is a shortcut to install the basic LAMP packages, so start by updating the repository data and installing the packages. Notice the "^" at the end of the command there - it is necessary:

apt-get update
apt-get upgrade
apt-get install lamp-server^

During this install you will be asked to choose a root password for MySQL. Choose something sensible, and then move on to adding an array of basic additional packages for PHP - such as APC bytecode caching, memcache support, cURL, an XML parser, and GD image processing. Add more to suite your own taste and the applications you want to support on this server.

apt-get install php-apc php5-memcache php5-curl php5-gd php-xml-parser

Configure PHP

The default configuration for PHP and the additional packages mentioned above is sufficient for most casual usage. So unless you have something complicated or high-powered in mind, you should probably only change the expose_php setting in /etc/php5/apache2/php.ini. Set it to "Off":

; Decides whether PHP may expose the fact that it is installed on the server
; (e.g. by adding its signature to the Web server header).  It is no security
; threat in any way, but it makes it possible to determine whether you use PHP
; on your server or not.
; http://php.net/expose-php
expose_php = Off

Configure Apache

The expected end result for Apache is that it will serve a single site with a couple of running web applications: webmail and Postfix Admin hidden away in a subdirectory. All traffic will be directed to HTTPS - there is no good reason to allow non-secure access to any of what will be on the web server.

Firstly configure the following lines in /etc/apache2/conf.d/security to minimize the information that Apache gives out in its response headers:

#
# ServerTokens
# This directive configures what you return as the Server HTTP response
# Header. The default is 'Full' which sends information about the OS-Type
# and compiled in modules.
# Set to one of:  Full | OS | Minimal | Minor | Major | Prod
# where Full conveys the most information, and Prod the least.
#
ServerTokens Prod
 
#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
#
ServerSignature Off

Make sure that mod_rewrite, mod_ssl, and the default SSL virtual host is enabled - you'll need these line items to be able to force visitors to use HTTPS.

a2enmod rewrite ssl
a2ensite default-ssl

The default site configuration in /etc/apache2/sites-available/default can be edited to look something like this for the sake of simplicity:

<VirtualHost *:80>
  ServerAdmin webmaster@localhost
 
  DocumentRoot /var/www
  <Directory "/">
    Options FollowSymLinks
    AllowOverride All
  </Directory>
 
  ErrorLog ${APACHE_LOG_DIR}/error.log
 
  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn
 
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

But of course your taste and needs may vary. Keeping the same simple approach, the upper portion of the SSL - configuration in /etc/apache2/sites-available/default-ssl can be set up as follows:

<IfModule mod_ssl.c>
  <VirtualHost _default_:443>
    ServerAdmin webmaster@localhost
 
    DocumentRoot /var/www
    <Directory "/">
      Options FollowSymLinks
      AllowOverride All
    </Directory>
 
    ErrorLog ${APACHE_LOG_DIR}/error.log
 
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
 
    CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
 
    #   SSL Engine Switch:
    #   Enable/Disable SSL for this virtual host.
    SSLEngine on
    #
 
    # ... more default SSL configuration ...
 
    # You will probably need to change this next Directory directive as well
    # in order to match the earlier one.
    <Directory "/">
      SSLOptions +StdEnvVars
    </Directory>
 
    # ... yet more default SSL configuration ...

If you are using a purchased rather than self-signed SSL certificate, and you probably have a CA certificate bundle from the issuer, then you'll want to further change these lines in /etc/apache2/sites-enabled/default-ssl:

#   A self-signed (snakeoil) certificate can be created by installing
#   the ssl-cert package. See
#   /usr/share/doc/apache2.2-common/README.Debian.gz for more info.
#   If both key and certificate are stored in the same file, only the
#   SSLCertificateFile directive is needed.
SSLCertificateFile    /path/to/my/cert.crt
SSLCertificateKeyFile /path/to/my/key.key
 
#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convinience.
SSLCertificateChainFile /path/to/my/ca-bundle.crt

To push visitors to HTTPS, put something similar to the following snippet into /var/www/.htaccess:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*) <nowiki>https://mail.example.com/$1</nowiki> [L]

Install and Configure Memcached

You will need to install Memcached to support the webmail applications intended to run on this server:

apt-get install memcached

The default configuration file at /etc/memcached.conf is good enough for a small server: it locks down access to localhost and provides generally sensible configuration parameter values. If you are building a larger machine for heavy usage, you will probably want to bump the memory allocation to be higher than the default of 64M:

# Start with a cap of 64 megs of memory. It's reasonable, and the daemon default
# Note that the daemon will grow to this size, but does not start out holding this much
# memory
-m 64

Install the Mailserver Packages

Now we're ready to start in on the harder stuff. As for the LAMP server, there is a shortcut for installing the basic packages for a mail server. Again, note the "^" at the end of the command:

apt-get install mail-server^

When Postfix installs, you will be asked to choose a general type of mail configuration - select "Internet site". You will be asked for the system mail name, which is the hostname of your mailserver - e.g. mail.example.com. What this gives you is pretty much just bare bones, aimed at a mailserver that manages its users as straightforward Unix users, and which doesn't use a SQL database to store data. So we need the rest of the cast - such as MySQL support for Postfix and Dovecot, and the coterie of spam-mashing packages. You might also have to install IMAP support for Dovecot, as it may or may not be included in the mail-server packages:

apt-get install postfix-mysql dovecot-mysql dovecot-imapd postgrey 
apt-get install amavis clamav clamav-daemon spamassassin
apt-get install php5-imap

The php5-imap package actually supports POP3 as well as the IMAP protocol, and will be needed by Postfix Admin and many of the possible options for PHP webmail applications. Restart Apache to have that running and ready:

 service apache2 restart

Next you'll want some optional packages that extend the abilities of the spam and virus detection packages, such as by allowing greater inspection of attached files:

apt-get install libnet-dns-perl pyzor razor
apt-get install arj bzip2 cabextract cpio file gzip nomarch pax unzip zip

You probably also want a package for dealing with RAR-format archives - but I've found unrar-free to be somewhat buggy and unstable, while unrar is not free. So you may just choose to skip that and shrug.

Create a Mail Database and User in MySQL

Log in to MySQL as the root user, entering the password you set earlier:

mysql -uroot -p

Now set up a database and user for the mail software. This database will store information on user accounts and mail domains, using schema set up by the Postfix Admin package:

create database mail;
grant all on mail.* to 'mail'@'localhost' identified by 'mailpassword';

Install Postfix Admin and the MySQL Schema

Postfix Admin is installed as follows. To start things off, download the package from Sourceforge, unpack it, and move it into a subdirectory of your webroot. You will probably also need to change ownership to the www-data user:

wget http://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-2.3.5/postfixadmin-2.3.5.tar.gz
gunzip postfixadmin-2.3.5.tar.gz
tar -xf postfixadmin-2.3.5.tar
mv postfixadmin-2.3.5 /var/www/postfixadmin
chown -R www-data:www-data /var/www/postfixadmin

Next is an interesting sort of a two-phase setup process. Firstly alter the following lines in /var/www/postfixadmin/config.inc.php:

/*****************************************************************
 *  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 * You have to set $CONF['configured'] = true; before the
 * application will run!
 * Doing this implies you have changed this file as required.
 * i.e. configuring database etc; specifying setup.php password etc.
 */
$CONF['configured'] = true;
// Postfix Admin Path
// Set the location of your Postfix Admin installation here.
// YOU MUST ENTER THE COMPLETE URL e.g. http://domain.tld/postfixadmin
$CONF['postfix_admin_url'] = 'https://mail.example.com/postfixadmin';
// Database Config
// mysql = MySQL 3.23 and 4.0, 4.1 or 5
// mysqli = MySQL 4.1+
// pgsql = PostgreSQL
$CONF['database_type'] = 'mysql';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'mail';
$CONF['database_password'] = 'mailpassword';
$CONF['database_name'] = 'mail';
// Site Admin
// Define the Site Admins email address below.
// This will be used to send emails from to create mailboxes.
$CONF['admin_email'] = 'me@example.com';
 
// Mail Server
// Hostname (FQDN) of your mail server.
// This is used to send email to Postfix in order to create mailboxes.
//
// Set this to localhost for now, but change it later.
$CONF['smtp_server'] = 'localhost';
$CONF['smtp_port'] = '25';
// Encrypt
// In what way do you want the passwords to be crypted?
// md5crypt = internal postfix admin md5
// md5 = md5 sum of the password
// system = whatever you have set as your PHP system default
// cleartext = clear text passwords (ouch!)
// mysql_encrypt = useful for PAM integration
// authlib = support for courier-authlib style passwords
// dovecot:CRYPT-METHOD = use dovecotpw -s 'CRYPT-METHOD'. Example: dovecot:CRAM-MD5
$CONF['encrypt'] = 'md5crypt';
// Mailboxes
// If you want to store the mailboxes per domain set this to 'YES'.
// Examples:
//   YES: /usr/local/virtual/domain.tld/username@domain.tld
//   NO:  /usr/local/virtual/username@domain.tld
$CONF['domain_path'] = 'NO';
// If you don't want to have the domain in your mailbox set this to 'NO'.
// Examples:
//   YES: /usr/local/virtual/domain.tld/username@domain.tld
//   NO:  /usr/local/virtual/domain.tld/username
// Note: If $CONF['domain_path'] is set to NO, this setting will be forced to YES.
$CONF['domain_in_mailbox'] = 'YES';

Next open up a web browser and visit your mail server at:

https://mail.example.com/postfixadmin/setup.php

Follow the instructions on that page to choose a setup password, and generate a hash of that password. Add that hash to the configuration file and save it:

// In order to setup Postfixadmin, you MUST specify a hashed password here.
// To create the hash, visit setup.php in a browser and type a password into the field,
// on submission it will be echoed out to you as a hashed value.
$CONF['setup_password'] = '...a long hash string...';

Then return to the setup page. You can now use the password you selected in order to create an initial administrator account. Postfix Admin will also automatically create its database schema at this point.

It is probably wise to restrict access to /var/www/postfixadmin/setup.php after having used it. Create a file /var/www/postfixadmin/.htaccess and put the following instructions into it:

<Files "setup.php">
deny from all
</Files>

Note that there is an annoying little issue involving the incorrect display of non-ASCII characters in Postfix Admin 2.3.5. It's easy to patch, however, so you may as well do that while you are here. Make the following small changes:

/var/www/postfixadmin/templates/list-virtual.php:

// Replacing this line:
// print "      <td>" . htmlentities($tMailbox[$i]['name']) . "</td>\n";
print "      <td>"
  . htmlentities($tMailbox[$i]['name'], ENT_QUOTES, 'UTF-8') 
  . "</td>\n";

/var/www/postfixadmin/templates/admin_list-domain.php:

// Replacing this line:
// print "<td>" . htmlentities($domain_properties[$i]['description']) . "</td>";
print "<td>"
  . htmlentities($domain_properties[$i]['description'], ENT_QUOTES, 'UTF-8') 
  . "</td>";

Create the Domain and Accounts in Postfix Admin

Now navigate to the main Postfix Admin login page:

 https://mail.example.com/postfixadmin/

Log in as the newly created administrator account, and then choose the "New domain" option under "Domain List" in order to create the example.com domain. You can then add mail users ("Add mailbox") and aliases ("Add alias") while viewing your domain. This will populate the schema, but it won't do anything else yet as none of the other mailserver components are configured to look at the database at this point.

Postfix Admin does have another useful function during this long setup process - it allows you to send mail to local users through the web interface, which is helpful when testing your configuration and chasing down errors.

Create a User to Handle Virtual Mail Directories

Virtual mail users are those that do not exist as Unix system users. They thus don't use the standard Unix methods of authentication or mail delivery and don't have home directories. That is how we are managing things here: mail users are defined in the database created by Postfix Admin rather than existing as system users. Mail will be kept in subfolders per domain and account under /var/vmail - e.g. me@example.com will have a mail directory of /var/vmail/example.com/me. All of these mail directories will be owned by a single user called vmail, and Dovecot will use the vmail user in order to create and update mail files.

useradd -r -u 150 -g mail -d /var/vmail -s /sbin/nologin -c "Virtual maildir handler" vmail
mkdir /var/vmail
chmod 770 /var/vmail
chown vmail:mail /var/vmail

Note that the user and virtual mail directory folder are using the "mail" group, and allowing other users in that group to modify the contents.

Configure Dovecot

Dovecot will manage IMAP and POP3 connections, local mail directories, and receive incoming mail handed off from Postfix. It will also manage authentication for SMTP connections - no point in having two separate authentication systems when Dovecot can handle both cases. Configuration is spread across a number of files in /etc/dovecot and subfolders thereof, and might seem a little intimidating, but it's all laid out fairly logically. The first thing to do is to ensure that Dovecot is looking for user data in the database created by Postfix Admin, so edit or create the file /etc/dovecot/conf.d/auth-sql.conf.ext to have the following contents:

# Look up user passwords from a SQL database as 
# defined in /etc/dovecot/dovecot-sql.conf.ext
passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}
# Look up user information from a SQL database as 
# defined in /etc/dovecot/dovecot-sql.conf.ext
userdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}

Now edit these lines in /etc/dovecot/dovecot-sql.conf.ext such that it uses the MySQL database created by Postfix Admin:

# Database driver: mysql, pgsql, sqlite
driver = mysql
# Examples:
#   connect = host=192.168.1.1 dbname=users
#   connect = host=sql.example.com dbname=virtual user=virtual password=blarg
#   connect = /etc/dovecot/authdb.sqlite
#
connect = host=localhost dbname=mail user=mail password=mailpassword
# Default password scheme.
#
# List of supported schemes is in
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
#
default_pass_scheme = MD5-CRYPT
# Define the query to obtain a user password.
password_query = \
  SELECT username as user, password, '/var/vmail/%d/%n' as userdb_home, \
  'maildir:/var/vmail/%d/%n' as userdb_mail, 150 as userdb_uid, 8 as userdb_gid \
  FROM mailbox WHERE username = '%u' AND active = '1'
# Define the query to obtain user information.
user_query = \
  SELECT '/var/vmail/%d/%n' as home, 'maildir:/var/vmail/%d/%n' as mail, \
  150 AS uid, 8 AS gid, concat('dirsize:storage=', quota) AS quota \
  FROM mailbox WHERE username = '%u' AND active = '1'

Then change the controlling definitions in /etc/dovecot/conf.d/10-auth.conf such that Dovecot will read the SQL configuration files. While you are there, you should also make sure that plaintext authentication is disabled unless the connection is encrypted or local:

# Disable LOGIN command and all other plaintext authentications unless
# SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP
# matches the local IP (ie. you're connecting from the same computer), the
# connection is considered secure and plaintext authentication is allowed.
disable_plaintext_auth = yes
# Space separated list of wanted authentication mechanisms:
#   plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey
#   gss-spnego
# NOTE: See also disable_plaintext_auth setting.
auth_mechanisms = plain login
##
## Password and user databases
##
 
#
# Password database is used to verify user's password (and nothing more).
# You can have multiple passdbs and userdbs. This is useful if you want to
# allow both system users (/etc/passwd) and virtual users to login without
# duplicating the system users into virtual database.
#
# <doc/wiki/PasswordDatabase.txt>
#
# User database specifies where mails are located and what user/group IDs
# own them. For single-UID configuration use "static" userdb.
#
# <doc/wiki/UserDatabase.txt>
 
#!include auth-deny.conf.ext
#!include auth-master.conf.ext
 
#!include auth-system.conf.ext
# Use the SQL database configuration rather than any of these others.
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-vpopmail.conf.ext
#!include auth-static.conf.ext

Next up, tell Dovecot where to put the virtual user mail directories. That requires the following changes in /etc/dovecot/conf.d/10-mail.conf:

# Location for users' mailboxes. The default is empty, which means that Dovecot
# tries to find the mailboxes automatically. This won't work if the user
# doesn't yet have any mail, so you should explicitly tell Dovecot the full
# location.
#
# If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u)
#  isn't enough. You'll also need to tell Dovecot where the other mailboxes are
# kept. This is called the "root mail directory", and it must be the first
# path given in the mail_location setting.
#
# There are a few special variables you can use, eg.:
#
#   %u - username
#   %n - user part in user@domain, same as %u if there's no domain
#   %d - domain part in user@domain, empty if there's no domain
#   %h - home directory
#
# See doc/wiki/Variables.txt for full list. Some examples:
#
#   mail_location = maildir:~/Maildir
#   mail_location = mbox:~/mail:INBOX=/var/mail/%u
#   mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
# 
# <doc/wiki/MailLocation.txt>
#
mail_location = maildir:/var/vmail/%d/%n
# System user and group used to access mails. If you use multiple, userdb
# can override these by returning uid or gid fields. You can use either numbers
# or names. <doc/wiki/UserIds.txt>
mail_uid = vmail
mail_gid = mail
# Valid UID range for users, defaults to 500 and above. This is mostly
# to make sure that users can't log in as daemons or other system users.
# Note that denying root logins is hardcoded to dovecot binary and can't
# be done even if first_valid_uid is set to 0.
#
# Use the vmail user uid here.
first_valid_uid = 150
last_valid_uid = 150

If you are bringing your own SSL certificate to the party, you have to let Dovecot know about by editing these lines in /etc/dovecot/conf.d/10-ssl.conf. Remember to include your CA certificate bundle if provided with one by the certificate issuer:

# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = yes
 
# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root. Included doc/mkcert.sh can be used to easily generate self-signed
# certificate, just make sure to update the domains in dovecot-openssl.cnf
ssl_cert = </path/to/my/cert.pem
ssl_key = </path/to/my/key.pem
 
# If key file is password protected, give the password here. Alternatively
# give it when starting dovecot with -p parameter. Since this file is often
# world-readable, you may want to place this setting instead to a different
# root owned 0600 file by using ssl_key_password = <path.
#ssl_key_password =
 
# PEM encoded trusted certificate authority. Set this only if you intend to use
# ssl_verify_client_cert=yes. The file should contain the CA certificate(s)
# followed by the matching CRL(s). (e.g. ssl_ca = </etc/ssl/certs/ca.pem)
#ssl_ca = </path/to/ca.pem

Next, edit these lines in /etc/dovecot/conf.d/10-master.conf to add the Postfix option:

service auth {
  # auth_socket_path points to this userdb socket by default. It's typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Its default
  # permissions make it readable only by root, but you may need to relax these
  # permissions. Users that have access to this socket are able to get a list
  # of all usernames and get results of everyone's userdb lookups.
  unix_listener auth-userdb {
   mode = 0600
    user = vmail
    group = mail
  }
 
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    # Assuming the default Postfix user and group
    user = postfix
    group = postfix        
  }

You may have to explicitly set a postmaster address in /etc/dovecot/conf.d/15-lda.conf; if you see "Invalid settings: postmaster_address setting not given" showing up in the mail log, then this is the fix for that. Make sure that a suitable alias or mailbox exists for your chosen postmaster address:

# Address to use when sending rejection mails.
# Default is postmaster@<your domain>.
postmaster_address = postmaster@example.com

You'll want to change the Dovecot configuration to be accessible to both dovecot and vmail users:

chown -R vmail:dovecot /etc/dovecot
chmod -R o-rwx /etc/dovecot

A final note on Dovecot: it only creates a user's mail directory when mail is first delivered to that virtual user. So creating a user in Postfix Admin will not result in the immediate creation of a mail directory under /var/vmail, and that's just fine.

Configure Postfix for MySQL

Postfix handles incoming mail via the SMTP protocol, and its configuration files have be set up to allow it to integrate with the various other packages we have installed so far. At a high level, we want Postfix to hand off incoming mail to the spam and virus checkers before passing it on to Dovecot for delivery, and to authenticate virtual users who are connecting over SMTP in order to to send mail.

Firstly create files describing for Postfix where to find information on users and domains. Note that the "hosts" directive in these files must be exactly the same as the "bind-address" in /etc/mysql/my.cnf. If one side says "localhost" and the other side says "127.0.0.1" then you may find that Postfix cannot connect to MySQL - strange but true. Here are the needed Postfix files:

/etc/postfix/mysql/virtual_alias_domainaliases_maps.cf

user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
query = SELECT goto FROM alias,alias_domain
  WHERE alias_domain.alias_domain = '%d'
  AND alias.address=concat('%u', '@', alias_domain.target_domain)
  AND alias.active = 1

/etc/postfix/mysql/virtual_alias_maps.cf

user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
table = alias
select_field = goto
where_field = address
additional_conditions = and active = '1'

/etc/postfix/mysql/virtual_domains_maps.cf

user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
table = domain
select_field = domain
where_field = domain
additional_conditions = and backupmx = '0' and active = '1'

/etc/postfix/mysql/virtual_mailbox_domainaliases_maps.cf

user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
query = SELECT maildir FROM mailbox, alias_domain
  WHERE alias_domain.alias_domain = '%d'
  AND mailbox.username=concat('%u', '@', alias_domain.target_domain )
  AND mailbox.active = 1

/etc/postfix/mysql_virtual_mailbox_maps.cf

user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
table = mailbox
select_field = CONCAT(domain, '/', local_part)
where_field = username
additional_conditions = and active = '1'

Now create the file /etc/postfix/header_checks, which will contain some directives to remove certain headers when relaying mail. This improves privacy for the sending users by such things as stripping the original IP address and mail software identifiers, for example. This file will be referenced in the main Postfix configuration:

/^Received:/                 IGNORE
/^User-Agent:/               IGNORE
/^X-Mailer:/                 IGNORE
/^X-Originating-IP:/         IGNORE
/^x-cr-[a-z]*:/              IGNORE
/^Thread-Index:/             IGNORE

The following is the complete main Postfix configuration file at /etc/postfix/main.cf, which contains a fair number of complex choices and options on how mail is relayed and how SMTP behaves. It is far beyond the scope of this post to explain each and every choice of best practice or configuration parameter in detail. I strongly suggest that you spend some time reading up on Postfix configuration, as this is where it is easy to fall down and produce a suboptimal or faulty mailserver.

Download main.cf

You must also add some material to /etc/postfix/master.cf, and here is the entire file for clarity, including much of the default material from the package install - such as commented options:

Download master.cf

Note that Amavis is restricted to two processes, which should be fine for most casual to moderate use. The processes are memory-heavy, so start low and add more only if you need to due to volume of mail - see the notes in this guide for pointers on how to do that.

Restart Everything, and Test the Server

Restart all the necessary processes to pick up configuration changes:

service postfix restart
service spamassassin restart
service clamav-daemon restart
service amavis restart
service dovecot restart

Now start testing! Keep an eye on /var/log/mail.err and /var/log/mail.log for error messages and try logging in to POP and IMAP, sending mail to an account created on the server, and sending mail from the server. If you find issues, then Google is your friend when it comes to searching on specific error messages in order to identify where the configuration is wrong, or when something unexpected crops up.