Creating a Mail Server on Ubuntu (Postfix, Courier, SSL/TLS, SpamAssassin, ClamAV, Amavis)

After the exposure and feedback I received from my previous guide, I felt it was about time you deserved an update.

This guide is now compatible with Ubuntu 13.04
For earlier versions: Creating a Mail Server on Ubuntu (Postfix, Courier, SSL/TLS, SpamAssassin, ClamAV, Amavis)

Once again, credit where credit due: Thanks again to Ivar Abrahamsen for his guide which is, by far, one of the best ones out there.

Getting Started

This guide is intended to be a reference for setting up a server quickly. For that reason, I have intentionally omitted information which explains each step. Please feel free to ask any questions in the comments and I’ll try to answer you as quickly as possible.

There are several configuration variables that you will need to replace in certain configuration files. These occurrences are clearly marked during the guide. However, for your reference, here are the variables used:

    The hostname for your mail server. This can be anything you like, however, it should match the public hostname as specified by your DNS records if you want to expose the server over the Internet.
  • rootpassword
    The password for the MySQL root user. You should pick something unique and secure; but something you can remember.
  • mailpassword
    The password for the MySQL mail user. You should pick something unique and secure; you don’t even have to remember it beyond this tutorial.
  • adminpassword
    The password for the administrator e-mail account that you’ll create later in the guide.


sudo su -
apt-get update
apt-get install -y mysql-server postfix postfix-mysql libsasl2-modules libsasl2-modules-sql libgsasl7 libauthen-sasl-cyrus-perl sasl2-bin libpam-mysql clamav-base libclamav6 clamav-daemon clamav-freshclam amavisd-new spamassassin spamc courier-base courier-authdaemon courier-authlib-mysql courier-imap courier-imap-ssl courier-pop courier-pop-ssl courier-ssl

Enter rootpassword.

Enter rootpassword.

Choose Ok.

Choose No.

Choose Ok.

Choose Internet Site.

Choose Ok.


Choose Ok.

Virtual User

Note: All e-mail messages will be received by a single ‘virtual’ user. That is, only one system account needs to be created and we’ll manage mailboxes using the virtual user features of Postfix.

groupadd virtual -g 5000
useradd -r -g "virtual" -G "users" -c "Virtual User" -u 5000 virtual
mkdir /var/spool/mail/virtual
chown virtual:virtual /var/spool/mail/virtual

Note that we are forcing the user ID to 5000 as this value is referenced by configuration files later. If you need to use a different UID make sure you update the affected configuration files, too.


mv /etc/postfix/{,.dist}
vi /etc/postfix/


myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name
biff = no
append_dot_mydomain = no
readme_directory = no
mydestination =
relayhost =
mynetworks = [::ffff:]/104 [::1]/128
mynetworks_style = host
mailbox_size_limit = 0
virtual_mailbox_limit = 0
recipient_delimiter = +
inet_interfaces = all
message_size_limit = 0
# SMTP Authentication (SASL)
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =
# Encrypted transfer (SSL/TLS)
smtp_use_tls = yes
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/ssl/private/
smtpd_tls_key_file = /etc/ssl/private/
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# Basic SPAM prevention
smtpd_helo_required = yes
smtpd_delay_reject = yes
disable_vrfy_command = yes
smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, reject
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject
# Force incoming mail to go through Amavis
content_filter = amavis:[]:10024
receive_override_options = no_address_mappings
# Virtual user mappings
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
virtual_mailbox_base = /var/spool/mail/virtual
virtual_mailbox_maps = mysql:/etc/postfix/maps/
virtual_uid_maps = static:5000
virtual_gid_maps =  static:5000
virtual_alias_maps = mysql:/etc/postfix/maps/
virtual_mailbox_domains = mysql:/etc/postfix/maps/
mv /etc/postfix/{,.dist}
vi /etc/postfix/


# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
# Do not forget to execute "postfix reload" after editing this file.
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
smtps     inet  n       -       -       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
submission inet n       -       -       -       -       smtpd
pickup    fifo  n       -       -       60      1       pickup
  -o content_filter=
  -o receive_override_options=no_header_body_checks
cleanup   unix  n       -       -       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  -       -       -       -       -       smtp
	-o smtp_fallback_relay=
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in maildrop_destination_recipient_limit=1
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
# See the Postfix UUCP_README file for configuration details.
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
# Other external delivery methods.
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix	-	n	n	-	2	pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/
  ${nexthop} ${user}
amavis    unix -        -       -       -       2       smtp
  -o smtp_data_done_timeout=1200
  -o smtp_send_xforward_command=yes
  -o disable_dns_lookups=yes
  -o max_use=20 inet n  -       -       -       -       smtpd
  -o content_filter=
  -o local_recipient_maps=
  -o relay_recipient_maps=
  -o smtpd_restriction_classes=
  -o smtpd_delay_reject=no
  -o smtpd_client_restrictions=permit_mynetworks,reject
  -o smtpd_helo_restrictions=
  -o smtpd_sender_restrictions=
  -o smtpd_recipient_restrictions=permit_mynetworks,reject
  -o smtpd_data_restrictions=reject_unauth_pipelining
  -o smtpd_end_of_data_restrictions=
  -o mynetworks=
  -o smtpd_error_sleep_time=0
  -o smtpd_soft_error_limit=1001
  -o smtpd_hard_error_limit=1000
  -o smtpd_client_connection_count_limit=0
  -o smtpd_client_connection_rate_limit=0
  -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

Virtual Maps

mkdir /etc/postfix/maps
vi /etc/postfix/maps/

Replace mailpassword

user = mail
password = mailpassword
dbname = mail
table = alias
select_field = destination
where_field = source
hosts =
additional_conditions = AND `enabled` = 1
vi /etc/postfix/maps/

Replace mailpassword

user = mail
password = mailpassword
dbname = mail
table = domain
select_field = domain
where_field = domain
hosts =
additional_conditions = AND `enabled` = 1
vi /etc/postfix/maps/

Replace mailpassword

user = mail
password = mailpassword
dbname = mail
table = user
select_field = CONCAT(SUBSTRING_INDEX(`email`, "@", -1), "/", SUBSTRING_INDEX(`email`, "@", 1), "/")
where_field = email
hosts =
additional_conditions = AND `enabled` = 1
chmod 700 /etc/postfix/maps/*
chown postfix:postfix /etc/postfix/maps/*

SASL Authentication (SSL/TLS)

usermod -aG sasl postfix
mkdir -p /etc/postfix/sasl
vi /etc/postfix/sasl/smtpd.conf

Replace mailpassword

pwcheck_method: saslauthd
auxprop_plugin: sql
mech_list: plain login
sql_engine: mysql
sql_user: mail
sql_passwd: mailpassword
sql_database: mail
sql_select: SELECT `password` FROM `user` WHERE `email` = "%u@%r" AND `enabled` = 1
mkdir -p /var/spool/postfix/var/run/saslauthd
mv /etc/default/saslauthd{,.dist}
vi /etc/default/saslauthd


DESC="SASL Authentication Daemon"
OPTIONS="-r -c -m /var/spool/postfix/var/run/saslauthd"
vi /etc/pam.d/smtp

Replace mailpassword

auth    required user=mail passwd=mailpassword host= db=mail table=user usercolumn=email passwdcolumn=password crypt=1
account sufficient user=mail passwd=mailpassword host= db=mail table=user usercolumn=email passwdcolumn=password crypt=1
chmod 700 /etc/postfix/sasl/smtpd.conf
chmod 700 /etc/pam.d/smtp


mv /etc/courier/authdaemonrc{,.dist}
vi /etc/courier/authdaemonrc


authmodulelistorig="authuserdb authpam authpgsql authldap authmysql authcustom authpipe"
mv /etc/courier/authmysqlrc{,.dist}
vi /etc/courier/authmysqlrc

Replace mailpassword

MYSQL_SERVER localhost
MYSQL_PASSWORD mailpassword
MYSQL_HOME_FIELD "/var/spool/mail/virtual"
MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(`email`, "@", -1), "/", SUBSTRING_INDEX(`email`, "@", 1), "/")
mv /etc/courier/imapd{,.dist}
vi /etc/courier/imapd


TCPDOPTS="-nodnslookup -noidentlookup"
mv /etc/courier/imapd-ssl{,.dist}
vi /etc/courier/imapd-ssl


mv /etc/courier/pop3d{,.dist}
vi /etc/courier/pop3d


TCPDOPTS="-nodnslookup -noidentlookup"
mv /etc/courier/pop3d-ssl{,.dist}
vi /etc/courier/pop3d-ssl



Note: In the next step you will be prompted to input some information about the certificate you create. You can enter any information you want here except Common Name (CN) which must match

openssl req -x509 -newkey rsa:1024 -keyout "/etc/ssl/private/" -out "/etc/ssl/private/" -nodes -days 3650
openssl req -new -outform PEM -out "/etc/ssl/private/" -newkey rsa:2048 -nodes -keyout "/etc/ssl/private/" -keyform PEM -days 3650 -x509
chmod 640 /etc/ssl/private/*
chgrp ssl-cert /etc/ssl/private/*


rm -f /etc/amavis/conf.d/50-user
vi /etc/amavis/conf.d/50-user


use strict;
$log_level = 1;
$syslog_priority = 'info';
$sa_kill_level_deflt = 6.5;
$final_spam_destiny = D_DISCARD;
$pax = 'pax';
@bypass_virus_checks_maps = (\%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);
@bypass_spam_checks_maps = (\%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);
@local_domains_acl = qw(.);


mv /etc/default/spamassassin{,.dist}
vi /etc/default/spamassassin


OPTIONS="--create-prefs --max-children 5 --helper-home-dir"


dpkg-reconfigure clamav-freshclam

Choose Ok.

Choose daemon.

Choose Ok.

Choose a mirror closest to your server.

Specify a proxy, if required.

Enter 24.

Choose No.

MySQL Database

mysql -uroot -p

Enter rootpassword.

Replace mailpassword

GRANT ALL ON `mail`.* TO "mail"@"localhost" IDENTIFIED BY "mailpassword";
USE `mail`;
  `source` VARCHAR(255) NOT NULL,
  `destination` VARCHAR(255) NOT NULL DEFAULT "",
  PRIMARY KEY (`source`)
  `domain` VARCHAR(255) NOT NULL DEFAULT "",
  `transport` VARCHAR(255) NOT NULL DEFAULT "virtual:",
  PRIMARY KEY (`domain`)
  `email` VARCHAR(255) NOT NULL DEFAULT "",
  `password` VARCHAR(255) NOT NULL DEFAULT "",
  PRIMARY KEY (`email`)

Create default data. This will:

  • Permit messages sent to the localhost domain
  • Permit messages sent to the localhost.localdomain domain
  • Permit messages sent to the domain
  • Create a mailbox for with the password adminpassword
  • Forward messages to the localhost.localdomain domain to the localhost domain
  • Forward messages to the localhost domain to

Replace and adminpassword

INSERT INTO `domain` (`domain`) VALUES ("localhost"), ("localhost.localdomain"), ("");
INSERT INTO `user` (`email`, `password`, `name`) VALUES ("", ENCRYPT("adminpassword"), "Administrator");
INSERT INTO `alias` (`source`, `destination`) VALUES ("@localhost.localdomain", "@localhost"), ("@localhost", "");

Finishing Up

Reboot Services

service saslauthd restart
service postfix restart
service courier-authdaemon restart
service courier-pop restart
service courier-pop-ssl restart
service courier-imap restart
service courier-imap-ssl restart

Create Your Mail Directory

You will not be able to login to your mailbox(es) until you create the required folder structure. There are two ways to do this:

  1. Send an e-mail to your new e-mail address from an existing e-mail account. Postfix will create the required directories for you.
  2. Create the directories yourself:

    mkdir -p /var/spool/mail/virtual/{new,tmp,cur}
    chown -R virtual:virtual /var/spool/mail/virtual/

About the Author: Adam Pancutt

I'm addicted to everything web: design, user interfaces, backend development and system administration. My expertise lies in the LAMP stack, UI development and scalability.

74 Comments + Add Comment

  • Quick question. Can i create a mail server with multiple domains?

    Like… and can use my as mail server?

    How to set up other mail “domains”?

    Thanks for the post btw :D

    • Sure. Each domain you want to use must exist in the ‘domain’ table in the database. You then need to either add mailboxes by adding rows to the ‘user’ table, or create forwarding rules in the ‘alias’ table.

      Example SQL snippets are available in the ‘MySQL Database’ section.

  • Hello, i was hoping you could help me figure this out,

    While connected to my local network everything works fine.

    But if i connect my computer over my 4g i can view / receive my email, but i cant send any out, it seems to connects fine with IMAP but it doesnt seem to work with stmp, the settings in Thunderbird are the same in both scenarios, so i dont think its an issue with the client

    ive also tried adding smtpd_client_restrictions = permit_sasl_authenticated to with no effect

    mail.log ( and x’s in place of actual names and ip’s)

    Sep 13 14:49:26 ubuntu-box imapd: Connection, ip=[]

    Sep 13 14:49:26 ubuntu-box imapd: LOGIN,, ip=[], port=[2658], protocol=IMAP

    Sep 13 14:50:02 ubuntu-box postfix/smtpd[20249]: connect from[]

    Sep 13 14:50:04 ubuntu-box postfix/smtpd[20249]: NOQUEUE: reject: RCPT from[]: 554 5.7.1 : Relay access denied; from= to= proto=ESMTP helo=

    but like i said this only happens when using a client that’s not on the same network as the server, but to send mail from clients on other computers on my network i had to edit mynetworks to [::ffff:]/104 [::1]/128

    so i think its something with sasl not authenticating, but i’m not sure.

    • Chris, see my comment below. If you have postfix version 2.10 or above, you need to add the following line to your -
      smtpd_relay_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
      This will enable mail relaying to Connections that successfully authenticate through SASL

  • I must say this is a very nice step-by-step tutorial to get everything you need on your LAMP stack at once.

    Minor flaw though, after running everything and carefully looking if I replaced everything necessary, it did not work. Now I’m clueless about where it went wrong and what pieces of this huge tutorial work on my server and which don’t.
    Time for a lot of debugging in everything together now, nevertheless its still faster then finding all this information myself :)

    Point of advice is adding some checks now and then to see if the previous “block” was executed correctly so we stay right on track.

    Keep up the good work, appreciated!

  • I have the same chris’ issue

  • I solved the issue adding

    smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination

    at the end of /etc/postfix/

  • Adam,
    I followed this guide, and was able to get it all working (after starting amavisd), aside from being able to send emails to external addresses when connected from another host outside my network.
    After researching online, I found that Postfix version =>2.10 needs to have another line added to /etc/postfix/ –
    smtpd_relay_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination

    Otherwise all attempts to relay email to an external address will fail.
    Might be worth adding to the guide, as well as a step to start amavisd?

    Hope this helps.

    • Hi Rob,

      I am having trouble amavis. Always displays ‘Connection refused’ when I try to fire it up.

      Can you guide me through the process of getting it to work?


  • Excellent Howto: I also ran into the need for the smtpd_relay_restrictions, I can send mail from an authenticated client now. Thank you.

    The issue I have seems to be with smtpd_sender_restrictions. Below is a reply mail from my hotmail to an email I sent from Note Sender address rejected.

    Sep 18 10:01:38 mail postfix/smtpd[383]: connect from[]
    Sep 18 10:01:38 mail postfix/smtpd[383]: NOQUEUE: reject: RCPT from[]: 554 5.7.1 : Sender address rejected: Access denied; from= to= proto=ESMTP helo=

    smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, reject

    I can comment out the smtpd_sender_restrictions and it works. I can also change “reject” to “permit” and it works. Neither seems an acceptable solution. Do I need the smtpd sender restrictions with spamassassin running? Suggestions?

    • I’ve ended up with the same problem; did you find any satisfactory solution?

  • […] Target Priority 10 On the VPS I used this step thru guide (…clamav-amavis/) setting to match […]

  • […] Target Priority 10 On the VPS I used this step thru guide (…clamav-amavis/) setting to match […]

  • Great job,
    I did the previous guide and found it is wonderful HowTo. My current mail is mostly built like your guide.

    But, please, can you update how to make quota?

  • Hi!
    Could you please publish proper Thunderbird settings which match this config?

    • My thunderbird can auto-detect like this, hope it works

      imap 143 startTLS nomal password
      smtp 587 startTLS nomal password

  • Hi, first at all THANKS. Very usefull guide.

    I’m new with this and I have some questions:

    How do I manage the accounts? (create user with password)
    To configure mi gmail account to download the emails (via POP) which port must I use? (110?)

    • I’ve just add the user with another insert INSERT INTO `user` (`email`, `password`, `name`) …

      but when I try to connect from my gmail account it shows me this error:

      “We were unable to locate the other domain. Please contact your other provider.”

    • I forgot to say that I’ve already added the mx record to my dns.
      Could it be due to the propagation? Or it is due to iptables issue someone talk some comments before.

  • I love your how-to however my postfix does not work how it suppose to.

    If i comment out restriction to mynetwork etc then pop3 works but in other case i cannot send to and from the server. i have smaller version then 2 of postfix.

    Send me what info you need.


    • Its really wierd. I can recieve email if comment out those lines (restrictions) even though i have 2< version of postfix and if I try to add the lines mentioned above it does not recognize those commands. POP3 works fine without the restrictions but smtp doesnt. Any idea? I think I did everything mentioned above…

  • […] This is technical but secure: configure and setup your own mail server and file syncing […]

  • Great guide!

    I’m almost there, I think. I’ve managed to get Thunderbird to autodetect my mail server, etc, but I’m getting an error when it’s attempting to test the username/password..

    “configuration could not be verified”

    I’ve tried using both ‘foo’ and ‘’ as username (for my address None works. And I’m using STARTTLS and normal password.

    Any idea where things might go wrong? Is it possible to test the username/password locally on the server somehow?

    • Solved this, I accidentaly used the wrong password when creating the ‘mail’ user for mysql. Now I’m able to connect to both imap and smtp from thunderbird.


      No e-mails are received:
      - I’ve tried to send an e-mail to myself using hotmail. But I receive the following message
      “: Sender address rejected: Access denied”

      No e-mails are sent
      - I can “send” emails using Thunderbird (no errors), but they don’t end up anywhere. I’ve tried e-mailing myself at, and I’ve tried to send e-mail to my hotmail. Neither message is received.

      Any ideas? Another misspelling?

      • So, I’m looking in the mail.log (/var/log/mail.log) at one of my attempts to send an email from one of my e-mail accounts to another:

        Oct 9 14:53:14 ubuntu postfix/smtpd[18228]: connect from[x.y.z.w]
        Oct 9 14:53:14 ubuntu postfix/smtpd[18228]: D70FAE1615:[x.y.z.w], sasl_method=PLAIN,
        Oct 9 14:53:15 ubuntu postfix/cleanup[18235]: D70FAE1615: message-id=
        Oct 9 14:53:15 ubuntu postfix/qmgr[18009]: D70FAE1615: from=, size=716, nrcpt=1 (queue active)
        Oct 9 14:53:15 ubuntu postfix/smtp[18223]: connect to[]:10024: Connection refused
        Oct 9 14:53:15 ubuntu postfix/smtp[18223]: D70FAE1615: to=, relay=none, delay=0.24, delays=0.24/0/0/0, dsn=4.4.1, status=deferred (connect to[]:10024: Connection refused)
        Oct 9 14:53:15 ubuntu postfix/smtpd[18228]: disconnect from[x.y.z.w]
        Oct 9 14:53:20 ubuntu pop3d: Connection, ip=[::ffff:]
        Oct 9 14:53:21 ubuntu pop3d: LOGIN,, ip=[::ffff:], port=[63615]
        Oct 9 14:53:21 ubuntu pop3d: LOGOUT,, ip=[::ffff:], port=[63615], top=0, retr=0, rcvd=12, sent=39, time=0, stls=1

        I believe the interesting part is the connection refused at “connect to[]“, where amavis should be running. At least according to my file.

        content_filter = amavis:[]:10024

        But when I look for amavis in netstat I don’t find anything..
        root@ubuntu:~# netstat -tap | grep amavis

        So. Any ideas on how to get the Amavis instance to run properly?
        Or am I looking at this the wrong way?

        • Problem solved! I can send- and receive messages from to using thunderbird!

          It turns out that Amavis wasn’t running. To get it running I had to follow these two steps:

          1) Edit /etc/amavis/conf.d/50-user
          sudo vi /etc/amavis/conf.d/50-user

          to add the following:
          $myhostname = ‘’;

          2) Start the service
          service amavis start

          Don’t know if the service will start automaticly from now on. But at least it’s running for now.

          Still seeing a few errors in the mail-log though..

          Oct 9 15:37:07 ubuntu amavis[18659]: (18659-02) ESMTP::10024 /var/lib/amavis/tmp/amavis-20131009T153106-18659: -> SIZE=742 BODY=8BITMIME Received: from ubuntu.localdomain ([]) by localhost ( []) (amavisd-new, port 10024) with ESMTP for ; Wed, 9 Oct 2013 15:37:07 +0200 (CEST)
          Oct 9 15:37:07 ubuntu amavis[18659]: (18659-02) Checking: J7zBVVuWgeRs [] ->
          Oct 9 15:37:07 ubuntu amavis[18659]: (18659-02) ClamAV-clamd: Can’t send to socket /var/run/clamav/clamd.ctl: Transport endpoint is not connected, retrying (1)
          Oct 9 15:37:08 ubuntu amavis[18659]: (18659-02) (!)ClamAV-clamd: Can’t connect to UNIX socket /var/run/clamav/clamd.ctl: No such file or directory, retrying (2)
          Oct 9 15:37:14 ubuntu amavis[18659]: (18659-02) (!)ClamAV-clamd av-scanner FAILED: run_av error: Too many retries to talk to /var/run/clamav/clamd.ctl (Can’t connect to UNIX socket /var/run/clamav/clamd.ctl: No such file or directory) at (eval 100) line 375.\n
          Oct 9 15:37:14 ubuntu amavis[18659]: (18659-02) (!!)WARN: all primary virus scanners failed, considering backups

          Anyone had the same problem with the AV?
          As I’m able to send e-mails I’m not looking into it right now. Might do it later though..

        • I’m seeing the same errors with AV and cannot for the life of me figure this out. Have you made any progress. Error are as follows:

          Feb 2 15:24:28 SERVER-02 amavis[1556]: (01556-01) (!)ClamAV-clamd: Can’t connect to UNIX socket /var/run/clamav/clamd.ctl: No such file or directory, retrying (2)
          Feb 2 15:24:34 SERVER-02 amavis[1556]: (01556-01) (!)ClamAV-clamd av-scanner FAILED: run_av error: Too many retries to talk to /var/run/clamav/clamd.ctl (Can’t connect to UNIX socket /var/run/clamav/clamd.ctl: No such file or directory) at (eval 100) line 375.\n
          Feb 2 15:24:34 SERVER-02 amavis[1556]: (01556-01) (!!)WARN: all primary virus scanners failed, considering backups

      • “Sender address rejected: Access denied” check your postfix configurate file:

        Look closely to the “#Basic spam preventions” this is the root of your problem. My configuration is slightly different from the guide, but it works.

        # Basic SPAM prevention

        smtpd_helo_required = yes
        smtpd_delay_reject = yes
        disable_vrfy_command = yes
        smtpd_sender_restrictions =
        smtpd_recipient_restrictions =

        smtpd_relay_restrictions = permit_mynetworks,

  • Plese make video of installation and webmail (

  • Excellent tutorial, thank you!!

    I’d love to see it fleshed out a little more with details on how to test the configuration (i.e. sending and receiving an email using the mail server) and also how to add new users (it looks like we’ve created, but how do i check admin’s emails?!) . Also some info on amending MX DNS records to make the whole thing work would be useful.

    Thanks again for helping me get this far anyway.


    • I managed to get it all working. To help others here are a few tips.

      1) Make sure you start Amavis and also add the smtpd_relay_restrictions config to as detailed by others in the comments above. You’ll also need to amend sender and recipient restrictions to permit external mail.

      2) To add users you need to add them to the mysql mail database. This can be done by adding to the database config you entered previously.


      mysql -u root -p
      use `mail`;
      INSERT INTO `user` (`email`, `password`, `name`) VALUES (“”, ENCRYPT(“newuser password”), “New User”);

      **amend newuser as appropriate and

      3) You’ll probably also need to create the directory structure as Courier didn’t do this for me automatically.

      mkdir -p /var/spool/mail/virtual/{new,tmp,cur}
      chown -R virtual:virtual /var/spool/mail/virtual/

      ** amend newuser and as appropriate

      4) You can see if the config is working by using sendmail and watching the ‘/var/spool/mail/virtual/’ directory. You should see emails being generated and be able to look at them using cat. If it doesn’t work check /var/log/mail.log to see what is happening.

      5) To access and send email of the virtual users you can use Thunderbird on your home PC/Mac. These account settings worked for me:

      Server Name =
      User Name = (i’m not sure if you need the so try without it if it doesn’t work)
      Protocol = IMAP
      Security = SSL/TLS
      Authentication = Normal Password
      Port = 993

      For SMTP use SSL/TLS, Normal Password and 465

      Note that you will need to make sure that these ports are open on your server firewall. Add ACCEPT rules to IPTABLES if not.

      If you are having issues with Thunderbird you can enable logging and view the logs when sending/receiving email.

      6) If you are still having issues double check that you have copied/pasted all of the tutorial config correctly. My /etc/pam.d/smtp file already had some config in. I foolishly left it and it took me a lot of troubleshooting to realise that it was causing an issue.

      7) After you’ve got it working use to make sure that you haven’t setup an openrelay or that your mailserver is blacklisted

      8) I forgot to mention that you also need to make sure that your DNS and MX records are setup correctly. You need to add an A record pointing to the IP Address of And then add an mx record for the domain pointing to DNS records may take 72 hours to update across the Internet so be patient. You can always use ping and whois and other tools to see if the updates have been applied yet.

      9) Good luck and don’t give up. It’s pretty sweet having the control of your own mail server once it is setup and by troubleshooting the config you learn how it works.

  • Just wanted to pop a comment on here and say a HUGE thank-you to Adam for this amazing guide, it’s been an absolute god send.

    I worked through it completely with my server, and now for the first time, I have access to emails on every domain I own! Ha, a small step for some, but for me it’s a huge achievement – so many many thanks.

  • In the MySQL configuration:
    GRANT ALL ON `mail`.* TO “mail”@”localhost” IDENTIFIED BY “mailpassword”
    I get the following problem: ACCESS DENIED FOR root@localhost (USING PASSWORD = YES)

    The MySQL-server only works when the –skip-grant-tables option is activated. So when I try to login without this option, I get an error. Now my problem is: How can I still run this command to use a mail server???

  • Hi,

    First off, thank you for the guide and all the time you invested in it. It’s been extremely helpful.

    I have a very (more than likely) simplistic question that either you or someone else may answer:

    I want to forward all mail sent to to I’ve attempted simply editing /etc/aliases but it doesn’t seem to work. Am I missing something?

    Thank you again.

    • I have the same issue. Did you figure it out? mail for bounces as the configuration only accepts email for Same for email sent to Therefore, I need to forward this mail to

    • To forward local email sent to root or www-data to the admin account just do:

      mysql -uroot -p
      USE `mail`;
      INSERT INTO `alias` (`source`, `destination`) VALUES (“”, “”), (“”, “”);

      It will only forward local email. If you send an email from external source to it will not redirect as the settings only allow email to

  • I tried to install the POSTfix , after Installed i checked the Status using
    sudo postfix status after getting

    postfix/postfix-script: the Postfix mail system is not running

    Please advice me

  • Very nice step-by-step tutorial.
    My telnet-test works fine :D But I can’t login with Thunderbird. The username or Password is wrong.. I have to use the data from my MySQL-Table, right? So the username is ‘Administrator’ and the proper password… I tried very much combinations, but everytime the same error.
    Have someone any idea?

    • I am having the same issue. It detects my email server and Thunderbird says “Connected to” but it keeps asking for a different password. I have created and tried several different accounts and passwords through MySQL and created a directory structure, but none of that seems to matter. I appended the fixes to the end of and followed all of David’s recommendations above.

      I can send emails to my accounts and they seem to go through, though nothing is appearing in the virtual user folders on the server. So there’s something wrong. I just can’t for the life of me figure out what. The installation went through without any errors, step by step.

      • Okay, I fixed the login issue. I miscopied something in /etc/courier/authmysqlrc so make certain all of those MySQL settings are correct.

        I can now add all of my email accounts to Thunderbird without an issue and it’s actually started to autodetect settings. The only remaining problem is sending/receiving emails as nothing I send to these addresses appears in the Inbox and attempting to send an email in Thunderbird presents this message:

        Sending of message failed.
        The message could not be sent because the connection to SMTP server timed out. Try again or contact your network administrator.

        One last thing to figure out.

  • How can we backup our saved mails ?

    They are not stored in DB ? Is there any other option then tar.gz the ‘new’ directory

  • is this guide compatible with ubuntu 10.04

  • is this guide compatible with ubuntu 10.04

  • hey i already have mysql installed ,what do i do to install the rest at a go

  • HI Adam,
    i have MySqlversion 5.1 installed.Please tell me where I can start from the above process.
    from the very start,what can I adjust in the installation you gave above?

    • still issue the code, it will pass the mysql installation if you have already installed

  • I came across this note in the procedure above:Make sure you have this subdomain configured in your DNS records.

    but in my case iam on a developer machine with no registered domain name,iam just trying to send out mail from my machine to other mail clients on line like yahoo,can i put any name here

  • HOW CAN I MAKE A DNS .since iam on a stand alone/remote machine and access internet on a dongle

    • If you are using a 3G or other dongle the chances of you having a static IP address are slim, which for outbound mail is rather important. You also tend to find that IP address for these type of connections (and many fixed connections too that run DHCP allocations) are listed in blacklists as they shouldn’t be used to send mail.

  • Just a note, you’ve updated this for Ubuntu 13.04 however as from the 27th Jan 2014 it (13.04) will be end of life and no longer get security patches. For important things like server people really should be using the LTS releases ( which continue to get supported updates (security and otherwise) for 5 years rather than the 9 months of the non-LTS releases.

    So if you’re looking for a long term supported system without so much pain from do-release-upgrade you might want to stick with 12.04 for now :)

  • Great tutorial Adam! The only question that I have and that it might be nice to add to the tutorial is how to add an account like that goes to /dev/null or that sends a response to the sender saying “This address does not accept mail” or something like that.

  • Hi there. I have a big problem.

    So email user: and password pass007

    When i loggin in just: and pass without 007.
    What a problem?

  • Hey.

    Great guide, finally set up my own mail server.
    I’ve used the mail app on my mac (OS X Mavericks) to connect to my new e-mail on the mail server and it receive mails just fine, but when i try to send mails nothing happens. In the mail log (/var/log/mail.log) on the server it says that:
    “SSL_accept error [IP]: lost connection

    Any advice as to what i need to edit/fix to make it work?

  • Thank so much you detail howto, I follow howto and config Ok on debian 6
    To get auto create imap folder working for new user i have to make some change as

    #chown virtual:postfix /var/spool/mail/virtual/
    #chmod 775 /var/spool/mail/virtual/

    and edit: /etc/courier/imapd with IMAP_MAILBOX_SANITY_CHECK=0

    #service courier-imap restart
    #service courier-imap-ssl restart

    When add new user i just create new user vi mysql and send one email to that user and that will be OK.

    I just wonder if this is a bad security issue since all auto create imap folder will change group owner by group postfix

  • Hey! nice guide dude, so many thanks, I added to my fav list :P

  • Whats the best way to test all the installed programs and components?

  • hey! i’ve followed all of your instructions, now i’m trying to use java to send a mail via my configured server, but somehow i always run into a 535 authentication failed-exception. my code looks like this:
    of course i replaced with my fqdn, and i tried “Administrator” as well as “mail” as usernames. do i miss something?

  • Hi and thanks for the tuto. Someone can tell me how to delete users in the mysql “user” table.
    I mean I used the given syntax (INSERT INTO `user` …) to create many test users and I want to delete these users.

    • Easy…
      DELETE FROM `user` WHERE name = “Dany”;

  • A huge thank you. Wanted to ask if you have additional instructions for postfix admin based on the details you provided here. Out of all things linux, mail servers is the one thing I have a challenge with.

    Many thanks, dvr

  • I followed your tutorial but getting error

    SASL LOGIN authentication failed: authentication failure

  • Hello All,

    I’m really new on Nagios. Hope someone will help me and figured out why i got an error, When I “service postfix restart”:

    fatal:/etc/mailname: file has 2 hard link

    I got stuck on this issue.

    Thank you in advance for all the reply.

  • Hello All,

    Great Guide ! Thank you so much.

    Everything is working fine for me so far.

    Although i cant send emails from e.g. googlemail to my mailserver.
    I get an access denied error.

    When i switch my
    smtpd_recipient_restrictions =permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination,permit

    Last Line: (reject to permit) -> i can recieve mails from googlemail , hotmail , …
    But this seems to be not acceptable as it opens a bit too much i guess ?

  • support is now dropped (see, apparently pam_mysql module has not been updated for quite some time. Looking to solve this some way atm, as my customers can’t send mail right now. This happened me with Ubuntu 12.04 LTS, with an system update (which seemed a bit odd as I did NOT do apt-get dist-upgrade).

    Just to get some SEO attention I’ll post here some lines from /var/log/auth.mail:
    Mar 7 20:04:44 myserver saslauthd[29018]: PAM unable to dlopen( /lib/security/ undefined symbol: make_scrambled_password_323
    Mar 7 20:04:44 myserver saslauthd[29018]: PAM adding faulty module:
    Mar 7 20:04:44 myserver saslauthd[29018]: DEBUG: auth_pam: pam_authenticate failed: Module is unknown
    Mar 7 20:04:44 myserver saslauthd[29018]: do_auth : auth failure: [] [service=smtp] [] [mech=pam] [reason=PAM auth error]

    • Problem solved , my own bad.

      I were using MariaDB (through MariaDB’s own repositories) and apt-get update did not honor distro depedencies, and thus picked up a version which had dropped support for pam_mysql. Removing MariaDB and installing MySQL was a hassle, but solved the problem.

  • Hello all,

    I need to find some attachments which sent to a mailbox of a user. I also tried to issue find / -name “abc.jpg” but it didnt find.

    How can I find the attachments which sent to the user ?


  • Hello,

    How can I set a catch-all email?
    I’ve tried to add record to alias -> but it didn’t worked. I received response email saying that the email was not delivered.

  • Hi everybody,
    like someone I also can’t figure out how to solve the:
    “SASL LOGIN authentication failed: authentication failure” error returned while trying to connect to the smtp and send a mail. My auth.log file contains:

    Mar 21 15:10:18 cosmonet postfix/smtpd[7505]: commit transaction
    Mar 21 15:10:18 cosmonet postfix/smtpd[7505]: sql plugin Parse the username
    Mar 21 15:10:18 cosmonet postfix/smtpd[7505]: sql plugin try and connect to a host
    Mar 21 15:10:18 cosmonet postfix/smtpd[7505]: sql plugin trying to open db ‘mail’ on host ’′
    Mar 21 15:10:18 cosmonet saslauthd[7361]: pam_unix(smtp:auth): check pass; user unknown
    Mar 21 15:10:18 cosmonet saslauthd[7361]: pam_unix(smtp:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=
    Mar 21 15:10:20 cosmonet saslauthd[7361]: DEBUG: auth_pam: pam_authenticate failed: Authentication failure
    Mar 21 15:10:20 cosmonet saslauthd[7361]: do_auth : auth failure: [] [service=smtp] [] [mech=pam] [reason=PAM auth error]

    I’ve spent about tree days playing with configuration files but with no luck. I’m able only to receive from outside the lan. If someone solved such a kind of behavior on ubuntu 13.10 please let me know.

  • Hello everybody again,
    and thank you so much Adam for sharing your great work.
    Related to my previous post if someone can help me I’ve used the testsaslauthd tool with the fallowing options:

    testsaslauthd -s smtp -u -p xxxxxxxx

    but it returns 0: NO “authentication failed”

    I’ve double checked the mysql tables data and the information stored into the configuration files, and everything seems quite right.

    Any help will be appreciated. Thanks

  • How can I implement reject_sender_login_mismatch ?

    I created in a line:
    but I don’t know to edit the file like in you example.


  • I have the following error when you restart the “courier-pop” service:

    service courier-pop restart
    * Stopping Courier POP3 server… [ OK ]
    * Starting Courier POP3 server… Unknown option ‘-pid=’

    I appreciate your help in advance

  • Excellent guide! I was able to get everything working. Now I’m adding a second domain, however whenever I send email from the second domain, it’s marked as spam because the headers says it’s received from my first domain. Any ideas how to fix this? Thanks a bunch!

    • can anyone help a girl out?

  • How do I access my email account? Do I need install any front-end application? Thanks

Leave a comment

Current day month ye@r *