Installing email with Postfix and Dovecot (with Postgres)

I’m posting my email setup here. The end result will:

  • Use Postfix for SMTP
  • Use Dovecot for IMAP and authentication
  • Store usernames, email forwards, and passwords in a Postgres SQL database
  • Only be accessible over encrypted channels
  • Pass all common spam checks
  • Support SMTP sending and IMAP email checking. I did not include POP3 because I don’t use it, but it should be easy to add
  • NOT add spam filtering or web mail (this article is long enough as it is, maybe in a follow-up)

Note: My set up is pretty standard, except that rDNS for resolves to because I only have one IP. You may need to change your hostnames if you’re using or

On to the install!

  1. Install debian packages
    sudo apt-get install postfix # Postfix \
          dovecot-core dovecot-imapd dovecot-lmtpd # Dovecot \
          postgresql dovecot-pgsql postfix-pgsql # Postgres \
          opendkim opendkim-tools # DKIM
  2. Set up security. cert is at /etc/certs/, the key is at /etc/ssl/private/ dhparams for postfix are at /etc/postfix/dhparams.pem. (If you need a certificate and don’t know how to get one, you can read Setting up SSL certificates using StartSSL)
  3. Install Postfix
    # /etc/postfix/
    smtp       inet  n       -       -       -       -       smtpd
    submission inet  n       -       -       -       -       smtpd
      -o syslog_name=postfix/submission
      -o smtpd_tls_security_level=encrypt
      -o smtpd_sasl_auth_enable=yes
      -o smtpd_reject_unlisted_recipient=no
      -o milter_macro_daemon_name=ORIGINATING
    # /etc/postfix/ additions
    # TLS parameters
    smtpd_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CDC3-SHA, KRB5-DE5, CBC3-SHA
    # Relay and recipient settings
    myhostname =
    myorigin = /etc/mailname
    mydestination =,,, localhost
    relayhost =
    mynetworks_style = host
    mailbox_size_limit = 0
    inet_interfaces = all
    smtpd_relay_restrictions = permit_mynetworks,
    alias_maps = hash:/etc/aliases
    local_recipient_maps = $alias_maps
    mailbox_transport = lmtp:unix:private/dovecot-lmtp
  4. Install Dovecot
    # /etc/dovecot/
    mail_privileged_group = mail # Local mail
    disable_plaintext_auth = no
    protocols = imap
    ssl_cert = </etc/ssl/certs/
    ssl_key = </etc/ssl/private/
    # IMAP Folders
    namespace {
     inbox = yes
     mailbox Trash {
     auto = create
     special_use = \Trash
     mailbox Drafts {
     auto = no
     special_use = \Drafts
     mailbox Sent {
     auto = subscribe
     special_use = \Sent
     mailbox Spam {
     auto = subscribe
     special_use = \Junk
    # Expunging / deleting mail should FAIL, use the lazy_expunge plugin for this
    namespace {
     prefix = .EXPUNGED/
     hidden = yes
     list = no
     location = maildir:~/expunged
    mail_plugins = $mail_plugins lazy_expunge
    plugin {
     lazy_expunge = .EXPUNGED/
    # /etc/postfix/
    # SASL authentication is done through Dovecot to let users relay mail
    smtpd_sasl_type = dovecot
    smtpd_sasl_path = private/auth
  5. Set up the database and virtual users. Commands
    # Create the user vmail for storing virtual mail
    # vmail:x:5000:5000::/var/mail/vmail:/usr/bin/nologin
    groupadd -g 5000 vmail
    mkdir /var/mail/vmail
    useradd -M -d /var/mail/vmail --shell=/usr/bin/nologin -u 5000 -g vmail vmail
    chown vmail:vmail /var/mail/vmail
    chmod 700 /var/mail/vmail
    psql -U postgres
    ; Set up the users
    ; Create the database
    \connect email
    ; Set up the schema 
    CREATE TABLE aliases (
        alias text NOT NULL,
        email text NOT NULL
    CREATE TABLE users (
        username text NOT NULL,
        domain text NOT NULL,
        created timestamp with time zone DEFAULT now(),
        password text NOT NULL
    GRANT ALL ON TABLE aliases TO postfix;
    GRANT ALL ON TABLE aliases TO dovecot;
    GRANT ALL ON TABLE users TO dovecot;
    GRANT ALL ON TABLE users TO postfix;
    # /etc/dovecot/dovecot.conf
    # Since we're giving each virtual user their own directory under /var/mail/vmail, just use that directly and not a subdirectory
    mail_location = maildir:~/
    # /etc/dovecot/dovecot-sql.conf defines the DB queries used for authorization
    passdb {
      driver = sql
      args = /etc/dovecot/dovecot-sql.conf
    userdb {
      driver = prefetch
    userdb {
      driver = sql
      args = /etc/dovecot/dovecot-sql.conf
    # /etc/postfix/
    local_recipient_maps = pgsql:/etc/postfix/ 
    # /etc/postfix/
    # hosts = localhost
    user = postfix
    password = XXXXXX
    dbname = email
    query = SELECT email FROM aliases WHERE alias='%s'
    # /etc/postfix/
    # hosts = localhost
    user = postfix
    password = XXXXXX
    dbname = email
    query = SELECT concat(username,'@',domain,'/') as email FROM users WHERE username='%s'
    # /etc/dovecot/dovecot-sql.conf
    driver = pgsql
    connect = host=localhost dbname=email user=dovecot password=XXXXXX
    default_pass_scheme = SHA512
    password_query = SELECT \
      CONCAT(username,'@',domain) as user, \
      password, \
      'vmail' AS userdb_uid, \
      'vmail' AS userdb_gid, \
      '/var/mail/vmail/%u' as userdb_home \
      FROM users \
      WHERE concat(username,'@',domain) = '%u';
    user_query = SELECT username, \
      CONCAT('maildir:/var/mail/vmail/',username,'@',domain) as mail, \
      '/var/mail/vmail/%u' as home, \
      'vmail' as uid, \
      'vmail' as gid \
      FROM users \
      WHERE concat(username,'@',domain) = '%u';
  6. Set up users. Example user creation:
    # Generate a password
    $ doveadm pw -s sha512 -r 100
    Enter new password: ...
    Retype new password: ...
    psql -U dovecot -d email
    ; Create a user
    mail=# INSERT INTO users (
    ) VALUES (
  7. Set up aliases/redirects. Example redirect creation:
    psql -U dovecot -d email
    ; Redirect mail from to
    mail=# INSERT INTO users ( email, alias ) VALUES (
  8. Test setup locally by hand. Try using TELNET. Test remote setup using STARTSSL. This is similar to the previous step, but to start the connection use:
    openssl s_client -connect -starttls smtp

    Make sure to test email to addresses at your domain or that you’ve set up (final destination), and emails you’re trying to send somewhere else (relay email)

    A small digression: port 25 is used for unencrypted email and support STARTTLS, 587 is used for STARTTLS only, and 465 (obsolete) is used for TLS. My ISP, Comcast, blocks access to port 25 on outgoing traffic.

  9. Make sure you’re not running an open relay at
  10. Set your DNS so that the MX record points at your new mailserver. You’ll probably want a store and forward backup mail server (mine is provided by my registrar). Email should arrive at your mail server from now on. This is the absolute minimum setup. Everything from here on is to help the community combat spam (and you not to get blacklisted).
  11. Set up DKIM (DomainKeys Identified Mail). DKIM signs outgoing mail to show that it’s from your server, which helps you not get flagged as spam.
    None of these files or folders exist to begin with in debian.

    # Add to /etc/opendkim.conf
    KeyTable                /etc/opendkim/KeyTable
    SigningTable            /etc/opendkim/SigningTable
    ExternalIgnoreList      /etc/opendkim/TrustedHosts
    InternalHosts           /etc/opendkim/TrustedHosts
    LogWhy yes
    # /etc/opendkim/TrustedHosts
    mkdir -p /etc/opendkim/keys/
    cd /etc/opendkim/keys/
    opendkim-genkey -s default -d
    chown opendkim:opendkim default.private
    # /etc/opendkim/KeyTable
    # /etc/opendkim/SigningTable

    Display the DNS public key to set in a TXT record with:

    # sudo cat /etc/opendkim/keys/
    default._domainkey      IN      TXT     ( "v=DKIM1; k=rsa; "
              "p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCggdv3OtQMek/fnu+hRrHYZTUcpUFcSGL/+Sbq+GffR98RCgabx/jjPJo3HmqsB8czaXf7yjO2UiSN/a8Ae6/yu23d7hyTPUDacatEM+2Xc4/zG+eAlAMQOLRJeo3z53sNiq0SmJET6R6yH4HCv9VkuS0TQczkvME5hApft+ZedwIDAQAB" )  ; ----- DKIM
    # My registrar doesn't support this syntax so it ends up looking like: 
    $ dig txt txt 10800 IN   TXT     "v=DKIM1\; k=rsa\; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCggdv3OtQMek/fnu+hRrHYZTUcpUFcSGL/+Sbq+GffR98RCgabx/jjPJo3HmqsB8czaXf7yjO2UiSN/a8Ae6/yu23d7hyTPUDacatEM+2Xc4/zG+eAlAMQOLRJeo3z53sNiq0SmJET6R6yH4HCv9VkuS0TQczkvME5hApft+ZedwIDAQAB"
    # Uncomment in /etc/default/opendkim
    SOCKET="inet:12345@localhost" # listen on loopback on port 12345
    # /etc/postfix/
    # DKIM
    milter_default_action = accept
    milter_protocol = 6
    smtpd_milters = inet:localhost:12345
    non_smtpd_milters = inet:localhost:12345
  12. Set up SPF (Sender Policy Framework). SPF explains to other services which IPs can send email on your behalf. You can set up whatever policy you like. A guide to the syntax is at:  Mine is
    @ 10800 IN TXT "v=spf1 ~all"

    You should also be verifying this on your end as part of combating spam, but as far as outgoing mail all you need to do is add a TXT record to your DNS record.

  13. Set your rDNS (reverse DNS) if it’s not already. This should point at the same hostname reported by Postfix during SMTP. This will be handled by whoever assigns your IP address (in my case, my hosting provider).
  14. Test your spam reputability using or You can monitor if you’re on any blacklists at
  15. Set up DMARC. DMARC declares your policy around DKIM being mandatory. You can set up whatever policy you like.  Mine is
    _dmarc 10800 IN TXT "v=DMARC1;p=reject;aspf=s;adkim=s;pct=100;"

My sources writing this:


  • You can set up store-and-forward mail servers, so if your mail server goes down, you don’t lose all the email for that period. It’s generally a free thing.
  • Postfix’s configuration files were badly designed and crufty, so you might pick a different SMTP server.
  • Email was REALLY not designed to do authentication, which is why proving you’re not a spammer is so difficult. This would all be trivial with decent crypto baked in (or really, almost any backwards-incompatible change)
  • The option to specify a SQL query as a configuration file option is wonderful. Thanks, Dovecot.
  • Overall, although it was a lot of work, I do feel like it was worth it to run my own email server.
Tagged , , , , , . Bookmark the permalink.

10 Responses to Installing email with Postfix and Dovecot (with Postgres)

  1. Pingback: Mail filtering with Dovecot - Optimal Prime

  2. eduardz says:


    Can you implement quota support from postgressql?

    • admin says:

      Not sure if this is “will you do” or “is it possible”. I will not do anything to set up quota–I have one user (me) so it doesn’t make sense. I encourage you to link if you do.

  3. Tudor says:

    In the “useradd -d -M -d /var/mail/vmail –shell=/usr/bin/nologin -u 5000 -g vmail vmail“ I think the first “-d“ shouldn’t be there

    Thanks for the post

  4. Tudor says:

    Also, for Postgresql the correct commands to create users are:

  5. Tudor says:

    Also, there shouldn’t be any comma after the VALUES (
    ‘{SHA512}…………………………………………………….==’ part

  6. S says:

    A little sloppy – you should have simply shown the entire contents of each file one by one, with descriptions in comments or whatever, instead of breaking them up into snippets – and there are a few errors and omissions (I can’t recall which ones now)
    However, using this guide and some googling, I was able to get a mailserver working – which is more than I can say for any other guide; so, thanks.

  7. Korilius says:

    A guide that could have been great but tripped at the finish line. A lot of errors in SQL and elsewhere along with step reorganization.

    • admin says:

      If you have any specific errors you can mention, I’d be happy to fix stuff.

      But yeah, that’s the problem with writing a guide after you do something instead of during/before.

Leave a Reply

Your email address will not be published. Required fields are marked *