server admin

Webmail on your Debian server: exim4 + dovecot + roundcube

2015 UPDATE: I discovered that dovecot now uses MUCH longer passwords than it used to, and the database tables I’d found online WILL FAIL to authenticate (they truncate your passwords!). Fixed below

95% of linux configuration on Debian servers is simple, well-documented, well-designed, easy to do, with only a tiny bit of reading of docs.

Sadly, “making email work” is most of the 5% that’s: nearly impossible, very badly designed, badly packaged/documented. This OUGHT to take an hour or two, in practice it takes ONE WEEK to setup. WTF? In 2014? Unacceptable!

So I took several incomplete/broken guides, dozens of pages of help and advice, and synthesized this complete, step-by-step guide. This should get you the webmail you actually want (!) in an hour or less.

What I wanted / what you probably want

These days, no-one has “only one domain”. If you’re running your own server(s), you should have many domains on a single server – this is normal, and Debian has long supported this out-of-the-box.

We want:

* Multiple domains using this for email (e.g.,,

* Webmail on your server (for anyone in the org to access email)

* Aliases / redirects for some email addresses (e.g. so you can redirect “support@” to a particular person)

* DO NOT create “linux users” for every email user – it’s a huge security hole, and a massive pain in the ass for the sysadmin

* DO NOT do mail-relaying

NB: when you’re supporting a significant number of users, and this is their main email address, you should do mail-relaying. I didn’t need it, so I haven’t tested it, and removed it from my instructions.

So, here we go…

How we’ll do it

We need five pieces of server-software:

  1. Web server
  2. Database server
  3. Email server (MTA)
  4. IMAP server
  5. Webmail server

When someone goes to a special web address, the webserver will open the webmail. When you login to webmail, it will talk to the IMAP server, which gives you a list of all your emails and lets you read them. When you try to send email (or receive it), the IMAP server will use the email server to do the send/receive work.

To make logins work without creating linux users for every possible account (and what if you have “” and “” ?? How do you fix that?) … we’ll use the database server to manage ALL logins and usernames/passwords.

Note: most of the other server-software ALREADY needs to use database software for their internal configuration – so we’ll have a database server hanging around already. Might as well use it!

We are using:

  • Debian = your OS (Ubuntu appears to be identical for all steps, but I haven’t tested it)
  • Apache v2 = web server (nginx etc would be faster, but Apache is the super-common server that all software already integrates with)
  • MySQL v5 = database server (postgres should be ALMOST identical config)
  • Exim v4 = your email-server
  • Dovecot = your IMAP server
  • Roundcube = your webmail server

To emphasize, we are NOT using:

  • NOT using: Postfix (slightly less common than exim?)
  • NOT using: Courier (WAY harder to configure/debug than Dovecot)
  • NOT using: Squirrel (ugly, hard to use), Horde (WAY too complicated for webmail)

Thanks to

The inspiration/starting point for this guide is Alex’s 4 years old exim3 “rough notes” – but don’t use this directly, it’s missing MORE THAN 50% of what you need!. I would have been lost with Alex’s starting point – way too much to discover – so I’m very grateful to him (you should be too :)).

I had done enough sysadmin in the past that I was confident I could fill in the bits Alex ommitted. I did – but it took a lot of time/effort :(.

Unexpected mentions

Exim4 – I hate exim configuration. It’s insane. Debian’s authors have tried to “sanitize” it but it will still make you weep.

Exim4 – …but: the “manual” on their website is comprehensive. It’s hard to read (too much jargon, too academic, too dense) – but it’s detailed and accurate. I hit a few very subtle problems that I eventually fixed by reading the manual chapters. But I had to re-read 4 or 5 times to understand what they were trying to say :(.

Dovecot – these guys maintain an amazingly good “check it’s working, and if not, isolate the problem” page. Every project should have one of these! It works *no matter what setup you’re using* (most projects say “if you didn’t compile from source, we won’t help you. Jog on!”. Have a look at this beauty … and also the super-short version (less useful).


Debian package maintainers did a bad job with the email packages. I believe this is a reflection of how exceptionally badly-designed the email apps are for linux: they defeated even the Debian maintainers!

Note: When you need multiple pieces of an app to make it work, Debian usually includes a set of “simple install” pacakges that automatically install the different combinations for you. That doesn’t work here – you have to be psychic (!) and know everything before you start. Ugh.

You need to install ALL of:

  1. apt-get install apache2-mpm-prefork
    • (Some of these email servers require PHP; PHP is crappy and requires mpm-prefork (the ‘slow’ version of Apache))
  2. apt-get install mysql-client
    • (should auto-install something like: mysql-common + mysql-client-5.5)
  3. apt-get install mysql-server
    • (should auto-install something like: mysql-server-5.5 + mysql-server-core-5.5)
  4. apt-get install exim4
  5. apt-get install exim4-base
  6. apt-get install exim4-config
  7. apt-get install exim4-daemon-heavy
    • (there’s an “exim4-mysql” that might be sufficient to replace this, but I gave up: there are way too many exim4 packages, and no help for installing the “correct” set, so … just pick this and get the lot!)
  8. apt-get install dovecot-core
  9. apt-get install dovecot-imapd
  10. apt-get install dovecot-mysql
  11. apt-get install roundcube
  12. apt-get install roundcube-core
  13. apt-get install roundcube-mysql

Setup: DNS

You should know about this already: you need an “MX” record on your DNS server, and it needs to point to your main server where you’ll run your email, web, etc.

Most people these days used hosted DNS, so the method to set this up will be specific to your hosting provider. It’s usually very simple.

Setup: Web server

By default, Roundcube sets up an over-the-top config: it creates an email server on every single website hosted on your server, and makes them all available at once.

Following the idea of, I used a much simpler, easier-to-maintain, and easier-to-secure setup. This is documented in the Debian package docs too.

Create a web address for your webmail

If you have multiple websites hosted on your server, you SHOULD have a separate file for each inside /etc/apache2/sites-available. e.g.:


For each domain that you want to give webmail to, edit the file and ADD the following:

<VirtualHost *:80>
ServerName webmail.[the domain name]

DocumentRoot /var/lib/roundcube

Note: replace “[the domain name]” with the domain name, e.g. “”


TinyMCE is a WYSIWYG text-editor for HTML emails. I hate it. It had a long history of being insecure, buggy, slow, and hard to use. So I disable it:

Edit /etc/roundcube/apache.conf:

Comment out these lines:

#<Directory "/usr/share/tinymce/www/">
# Options Indexes MultiViews FollowSymLinks
# AllowOverride None
# Order allow,deny
# allow from all

Setup: create databases

Create your databases. From the command-line, you can do something like:

mysql -u root -p

…or use your preferred softare (e.g. phpMyAdmin).

Create the database

CREATE DATABASE email_accounts;

Create the tables for email-accounts and config

NOTE: some places on web list varchar(50) for the password – with MySQL and dovecot latest, that’s too short, and the DB will return truncated passwords, blocking your users from logging in

USE email_accounts;

CREATE TABLE mailboxes (
domain_id INT(10) NOT NULL,
local_part VARCHAR(250) NOT NULL,
password VARCHAR(100) NULL,
description VARCHAR(250) NULL,
CREATE TABLE aliases (
domain_id INT(10) NOT NULL,
local_part VARCHAR(250) NOT NULL,
description VARCHAR(250) NULL,
CREATE TABLE vacations (
mailbox_id INT(10) NOT NULL,
subject VARCHAR(250) NOT NULL,
description VARCHAR(250) NULL,

CREATE TABLE domains (
type ENUM(‘local’,’relay’) NOT NULL DEFAULT ‘local’,
description VARCHAR(250) NULL,

Create a database-account to access the database

grant ALL on email_accounts.* to ’email’@’localhost’ identified by ‘password’;
flush privileges;

Note: that is not an email address, it’s a MySQL user account.
Note: this account will ONLY be accessible by our software running on the server; you cannot access this account remotely (over the internet).

Create your first email account and domain

INSERT INTO domains VALUES(NULL,’’,’local’,’My nice domain for local delivery’,1,NOW(),NOW());

INSERT INTO mailboxes VALUES(NULL,1,’joe’,MD5(‘password – choose a good one’),’My account for’,1,NOW(),NOW());

Note: this password is used over the internet when you login to webmail – so pick a good one! This has to be secure!

Create a redirector for an email address

insert into aliases values (null, 1, ‘support’, ‘’, ‘Redirecting support@ to the CEO. It will be a good experience’, 1, NOW(), NOW() );

Note: only set this up if you actually want a redirect.

Setup: Configure Exim4

When you install Exim4, make sure you chose the “split” packages. If not, you can fix that now by running:

dpkg-reconfigure exim4-config

See the next section for the answers to fields, but edit that file afterwards to check you got it right.

Debian: set the global / initial Exim config

NB: these are the settings filled out by “dpkg-reconfigure exim4-config”. Here’s what your file should look like:

Edit: /etc/exim4/update-exim4.conf.conf

# /etc/exim4/update-exim4.conf.conf
# Edit this file and /etc/mailname by hand and execute update-exim4.conf
# yourself or use ‘dpkg-reconfigure exim4-config’
# Please note that this is _not_ a dpkg-conffile and that automatic changes
# to this file might happen. The code handling this will honor your local
# changes, so this is usually fine, but will break local schemes that mess
# around with multiple versions of the file.
# update-exim4.conf uses this file to determine variable values to generate
# exim configuration macros for the configuration file.
# Most settings found in here do have corresponding questions in the
# Debconf configuration, but not all of them.
# This is a Debian specific file

dc_other_hostnames='[YOUR DOMAIN 1];[YOUR DOMAIN 2]’
dc_local_interfaces=’;[PUT YOUR SERVER’s IP ADDRESS HERE]’

Note: replace “[YOUR DOMAIN 1]” with e.g. “”, or “” – you must have one of these for EACH of your domains which has email accounts.
Note: replace “[PUT YOUR SERVER’s IP ADDRESS HERE]” with e.g. “” (whatever your public internet address is)

Setup Exim: Macros

ADD the following to /etc/exim4/conf.d/main/000_localmacros:

MAIN_LOCAL_DOMAINS = @:localhost:dsearch;/etc/exim4/virtual:${lookup mysql{SELECT fqdn AS domain FROM domains WHERE fqdn=’${quote_mysql:$domain}’ AND type=’local’ AND active=1}}

ADD the following to /etc/exim4/conf.d/main/01_exim4-config_listmacrosdefs:

# List of domains considered local for exim. Domains not listed here
# need to be deliverable remotely.
domainlist local_domains = MAIN_LOCAL_DOMAINS

# MySQL because exim4 on Debian doesn’t always add this:


Note: “hide mysql_servers” isn’t “hiding” anything – it’s an ESSENTIAL step! It actually means “use this database server”. Terrible config name :(.

Setup Exim: Routers

CREATE the file /etc/exim4/conf.d/router/360_exim4-config_mysqlusers:

driver = accept
condition = ${lookup mysql{SELECT CONCAT(mailboxes.local_part,’@’,domains.fqdn) AS goto FROM domains,mailboxes WHERE \
mailboxes.local_part=’${quote_mysql:$local_part}’ AND \ AND \ AND \
domains.fqdn=’${quote_mysql:$domain}’ AND \}{yes}{no}}
transport = dovecot_delivery

Either DELETE this file, or comment-out all lines /etc/exim4/conf.d/router/400_exim4-config_system_aliases:

### router/400_exim4-config_system_aliases

# This router handles aliasing using a traditional /etc/aliases file.
##### NB You must ensure that /etc/aliases exists. It used to be the case
##### NB that every Unix had that file, because it was the Sendmail default.
##### NB These days, there are systems that don’t have it. Your aliases
##### NB file should at least contain an alias for "postmaster".
# This router handles the local part in a case-insensitive way which
# satisfies the RFCs requirement that postmaster be reachable regardless
# of case. If you decide to handle /etc/aliases in a caseful way, you
# need to make arrangements for a caseless postmaster.
# Delivery to arbitrary directories, files, and piping to programs in
# /etc/aliases is disabled per default.
# If that is a problem for you, see
# /usr/share/doc/exim4-base/README.Debian.gz
# for explanation and some workarounds.

# debug_print = "R: system_aliases for $local_part@$domain"
# driver = redirect
# domains = +local_domains
# allow_fail
# allow_defer
# data = ${lookup{$local_part}lsearch{/etc/aliases}}
# .endif
# .endif
# .endif
# .endif
# .endif

CREATE this file /etc/exim4/conf.d/router/401_exim4-config_mysql_aliases:

### router/401_exim4-config_mysql_aliases

# ADAM: This router handles aliasing using the proprietary mysql setup
# c.f.

driver = redirect
data = ${lookup mysql{SELECT aliases.goto AS goto FROM domains,aliases WHERE \
(aliases.local_part=’${quote_mysql:$local_part}’ OR aliases.local_part=’@’) AND \ AND \ AND \
domains.fqdn=’${quote_mysql:$domain}’ AND \}}

Setup exim: Transports

CREATE / OVERWRITE the file /etc/exim4/conf.d/transport/30_exim4-config_dovecot:
### transport/30_exim4-config_dovecot


driver = appendfile
maildir_format = true
directory = /var/spool/mail/$domain/$local_part
create_directory = true
directory_mode = 0770
mode_fail_narrower = false
message_prefix =
message_suffix =
user = mail
group = mail
mode = 0660

Setup exim: Auth

CREATE the file /etc/exim4/conf.d/auth/20_exim4-config_mysql-authenticator:


driver = plaintext
public_name = PLAIN
server_condition = ${lookup mysql{SELECT CONCAT(mailboxes.local_part,’@’,domains.fqdn) FROM mailboxes,domains WHERE \
mailboxes.local_part=SUBSTRING_INDEX(‘${quote_mysql:$auth2}’,’@’,1) AND \
mailboxes.password=MD5(‘${quote_mysql:$auth3}’) AND \ AND \ AND \
domains.fqdn=SUBSTRING_INDEX(‘${quote_mysql:$auth2}’,’@’,-1) AND \}{yes}{no}}
server_prompts = :
server_set_id = $auth2

driver = plaintext
public_name = LOGIN
server_condition = ${lookup mysql{SELECT CONCAT(mailboxes.local_part,’@’,domains.fqdn) FROM mailboxes,domains WHERE \
mailboxes.local_part=SUBSTRING_INDEX(‘${quote_mysql:$auth1}’,’@’,1) AND \
mailboxes.password=MD5(‘${quote_mysql:$auth2}’) AND \ AND \ AND \
domains.fqdn=SUBSTRING_INDEX(‘${quote_mysql:$auth1}’,’@’,-1) AND \}{yes}{no}}
server_prompts = Username:: : Password::
server_set_id = $auth1

Setup: Configure Dovecot

When installing the dovecot apts, make sure you chose the “split files” option (exactly as with Exim4). It makes life easier. If you got this wrong, run:

dpkg-reconfigure dovecot-core

Note: Dovecot installs with almost everything “Commented out”. Many of these options exist commented-out, you should find them in the config file, and put your “new” values on the line below, so it’s easy in future to find them and see which “defaults” you changed.

Dovecot: find your “mail” linux user

For security, you want a “mail” user account that runs your server-software, and has restricted access to your server. Debian auto-creates this, but you need to find out what uid and gid it has.

To find these out do:

cat /etc/passwd

…and find the line something like:


the first 8 is your uid, the second 8 is your gid (could be different numbers on your server)

Dovecot: all config files

ADD to the file /etc/dovecot/dovecot.conf:

protocols = imap
listen = *, ::

Add to the file /etc/dovecot/conf.d/10-mail.conf:
mail_location = maildir:~
ADD to the file /etc/dovecot/conf.d/10-auth.conf:
!include auth-sql.conf.ext

ADD to the file /etc/dovecot/dovecot-sql.conf.ext:
connect = host= dbname=email_accounts user=email password=password
default_pass_scheme = MD5

password_query = SELECT CONCAT(mailboxes.local_part,’@’,domains.fqdn) as `user`, mailboxes.password AS `password`,’/var/spool/mail/%d/%n’ AS `userdb_home`, [YOUR UID] AS `userdb_uid`, [YOUR GID] AS `userdb_gid` FROM `mailboxes`, `domains` WHERE mailboxes.local_part = ‘%n’ AND = 1 AND mailboxes.domain_id = AND domains.fqdn = ‘%d’ AND = 1

user_query = SELECT ‘/var/spool/mail/%d/%n’ AS `home`, [YOUR UID] AS `uid`, [YOUR GID] AS `gid`

Note: replace [YOUR UID] and [YOUR GID] with correct numbers (that you found out using cat /etc/passwd)

Setup: Configure Roundcube

EDIT the file /etc/roundcube/
$rcmail_config[‘default_host’] = ‘[YOUR MX RECORD]’;
Note: replace “[YOUR MX RECORD]” with the MX address you put on your DNS server at the very start. e.g. “”.

In that file, there are instructions on how to make it automatically calculate the address using %n, %d, etc. If your MX records for your different domains follow the same pattern (e.g. they are all “”), and your webmail login addresses all follow the same pattern (e.g. “”), you can put one string here and it will automatically log people into the right server in every case, based on the URL they visited.


Now you’ve set it up, you MUST restart the web and email servers.

You must ALSO do this everytime you change any config files!

/etc/init.d/apache2 restart
/etc/init.d/exim4 restart
/etc/init.d/dovecot restart

Exim may output a “paniclog”. If so, read it, fix it – and then manually delete the paniclog file, or else you’ll keep getting fake warnings every time you restart exim.

Debugging – making it work!

You’ve got a lot to test here!

Test exim

receiving emails

Pick an email address that you added to the “email_accounts” database, and try sending email to it while logged-in to server command-line:
exim -d -bt
…this will give a COMPLETE list of what exim is doing, and it will tell you every decision it made along the way. It should eventually decide the address is “routeable” and OK it.

If that looks OK, try sending an email from your normal email account (e.g. your Hotmail / Gmail / address). Wait a minute, then check the server to see if it crashed trying to receive the email, by checking the logfiles.

Check exim’s logfiles

Exim will put its logfiles in /var/log/exim4. Check for errors using:
tail /var/log/exim4/mainlog
(if there’s a lot of errors, you’ll have to cat the whole thing)

If it rejected the email, it will send a bounce-back to your email provider (yahoo/gmail/etc), and it will ALSO put some info into:
tail /var/log/exim4/rejectlog

sending emails

…I waited until I had webmail (Roundcube) working before trying this…

Any other Exim problems?

If exim is working, but its blocking/rejecting/losing emails, it will “freeze” them after the first failure. You need to “unfreeze” (i.e. retry) each email to see if you’ve fixed the problem.


Here is a list of commands to help:

Test Dovecot

Dovecot’s maintainers have written an excellent step-by-step guide to testing it, with copy/pasteable command-lines

Note: to make this work, I had to install telnet: “apt-get install telnet-client”

Test Roundcube

Go to the web-address you configured at the very start (e.g. “”). It should give you a login page for Roundcube.

Login using the user-account you crated in MySQL at the start, using the FULL email address, e.g.:

Username: “”
Password: “password – choose a good one”

If you set things up correctly, following my steps above, it should NOT ask you for an IMAP server. If it does … go back and read this post more carefully.

You should find yourself in webmail, able to send emails, and receive them.

If it all works … speed it up!

Out of the box, Roundcube runs very, very, very slowly … because it checks lots of different passwords before asking MySQL to check the password.

Fortunately there’s a very quick fix here:

After doing that, I found webmail go from “takes 5 seconds per click” to “most clicks have immediate effect” (on my fast broadband).

What you should do next…

This setup gets you decent, working, webmail. This is the hardest bit!

But it’s missing some core features you’ll want to add next:

  1. Reduce incoming spam: install SpamAssassin or similar
  2. Secure the webmail connection: buy an SSL certificate, install it in Apache, force webmail to use SSL/TLS.
  3. Secure the IMAP connection: the setup above allows anyone to IMAP to the server from public internet. This allows you to use Outlook etc as a mail client. But if you *only* want to allow Webmail, you can edit your Dovecot configs and change the “listen” setting to only listen on / localhost. This will allow Roundcube to connect (it’s on the same server) but will block internet clients.

…those should be easy to find separate guides for. Good luck.

2016 Update

Michael Radhuber reports following changes needed for Ubuntu 15.10 (may be needed for some other Debian’s, but I didn’t need them with stock Debian):

Only two things I might add:
1. In the file /etc/dovecot/conf.d/auth-sql-conf.ext uncomment driver and set it to mysql
2. /etc/dovecot/conf.d/10-mail.conf uncomment first_valid_uid and set it to [your_uid] (ie. 8). If you need to do the same for first_valid_gid

10 replies on “Webmail on your Debian server: exim4 + dovecot + roundcube”

I make a doc like this every time I set up MY email server ;)

If you get any quantity of spam at all, you should consider greylisting. It is still remarkably effective although not as effective as it used to be. Much better than I ever did with spamassassin.

Awesome tutorial.
Only two things I might add:
1. In the file /etc/dovecot/conf.d/auth-sql-conf.ext uncomment driver and set it to mysql
2. /etc/dovecot/conf.d/10-mail.conf uncomment first_valid_uid and set it to [your_uid] (ie. 8). If you need to do the same for first_valid_gid

You might have the wrong version of exim? (guess)

The default exim in Debian is nerfed, missing a whole bunch of core stuff. I’ve had strange (as well as expected) errors from using that in the past.

When i restart exim4 i have this error:
[….] Stopping MTA for restart:2014-09-30 20:11:22 Exim configuration error in line 22 of /var/lib/exim4/config.autogenerated.tmp:
main option “mysql” unknown
Invalid new configfile /var/lib/exim4/config.autogenerated.tmp, not installing
/var/lib/exim4/config.autogenerated.tmp to /var/lib/exim4/config.autogenerated

As per instructions, Yu must install the correct version of exim4, not the default nerfed one

What is it mean the “correct version of exim 4”? Perhaps Do I have to purge my exim4 installation to install the latest source of exim 4 from the exim4 website and compile it? In this tutorial you have not explaned this point…

Hi, while restarting exim I’m getting:

Stopping MTA for restart:2014-10-01 14:40:07 Exim configuration error in line 105 of /var/lib/exim4/config.autogenerated.tmp:
duplicate name "local_domains" for a named domain list
Invalid new configfile /var/lib/exim4/config.autogenerated.tmp, not installing
/var/lib/exim4/config.autogenerated.tmp to /var/lib/exim4/config.autogenerated

What to do now?

These are ultra-basic questions.

I’m closing this post to comments. This is not a help forum for “people who can’t follow instructions, and can’t debug their own mistakes”.

If your response to being told “you made a mistake in this line number, in this file” is “I don’t know what to do”, you shouldn’t be setting up mail services – the complexities of a modern mailserver are going to screw you over badly (not your fault! – mailservers are needlessly over-complicated, viciously difficult to configure, and unforgiving).

Instead, you should spend some time mastering basic sysadmin first (skills like debugging config mistakes, debugging “wrong package” mistakes”, etc)

Comments are closed.