Setting up your own email server on Linux from scratch is a pain in the butt, if you are not an advanced user. This tutorial will be showing you how to use iRedMail to quickly set up a full-featured mail server on Ubuntu 18.04, saving you lots of time and headaches.

What is iRedMail?

iRedMail is a shell script that automatically install and configure all necessary mail server components on your Linux/BSD server, thus eliminating manual installation and configuration. With iRedMail, you can easily create unlimited mailboxes and unlimited mail domains in a web-based admin panel. Mailboxes can be stored in MariaDB/MySQL, PostreSQL database or OpenLDAP. Open-source software used in iRedMail are as follows:

  • Postfix SMTP server
  • Dovecot IMAP server
  • Nginx web server
  • OpenLDAP, ldapd
  • MySQL/MariaDB, PostgreSQL
  • Amavised-new
  • SpamAssassin
  • ClamAV
  • Roundcube webmail
  • SOGo Groupware
  • Fail2ban
  • mlmmj mailing list manager
  • Netdata server monitoring
  • iRedAPD Postfix policy server for greylisting

Step 1: Choose the Right Hosting Provider and Buy a Domain Name

To set up a complete email server with Modoboa, you need a server with at least 2GB RAM, because after the installation, your server will use more than 1GB of RAM. This tutorial is done on a $8.99/month Hostwinds VPS (virtual private server). I recommend Hostwinds because it does not block port 25, so you can send unlimited emails (transactional email and newsletters) without spending money on SMTP relay. Hostwinds doesn’t have any SMTP limits. You can send a million emails per day.

Other VPS providers like DigitalOcean blocks port 25. DigitalOcean would not unblock port 25, so you will need to set up SMTP relay to bypass blocking, which can cost you additional money. If you use Vultr VPS, then port 25 is blocked by default. They can unblock it if you open a support ticket, but they may block it again at any time if they decide your email sending activity is not allowed. Vultr actually may re-block it if you use their servers to send newsletters.

Go to Hostwinds website to create an account. Choose the 2GB unmanaged Linux VPS plan.

Once you created an account, Hostwinds will send you an email with the server SSH login details. To log into your server, you use an SSH client. If you are using Linux or macOS on your computer, then simply open up a terminal window and run the following command to log into your server. Replace 12.34.56.78 with your server’s IP address.

ssh [email protected]

You will be asked to enter the password. If you are using Windows, please read the following article on how to use SSH client.

It is recommended that you follow the instructions below on a clean install of Ubuntu 18.04 system. Installing a piece of complex server software like Modoboa on a non-LTS Ubuntu is discouraged as you will probably encounter problems when upgrading your OS every 9 months. The software author doesn’t have time to support every Ubuntu release. It is far better for your mail server to stay stable for 2 or 5 years.

You also need a domain name. I registered my domain name from NameCheap because the price is low and they give whois privacy protection free for life.

Step 2: Creating DNS MX Record

The MX record specifies which host or hosts handle emails for a particular domain name. For example, the host that handles emails for linuxbabe.com is mail.linuxbabe.com. If someone with a Gmail account sends an email to [email protected], then Gmail server will query the MX record of linuxbabe.com. When it finds out that mail.linuxbabe.com is responsible for accepting email, it then query the A record of mail.linuxbabe.com to get the IP address, thus the email can be delivered.

In your DNS manager, create a MX record for your domain name. Enter @ in the Name field to represent the main domain name, then enter mail.your-domain.com in the Value field.

Note: The hostname for MX record can not be an alias to another name. Also, It’s highly recommended that you use hostnames, rather than bare IP addresses for MX record.

Your DNS manager may require you to enter a preference value (aka priority value). It can be any number between 0 and 65,356. A small number has higher priority than a big number. You can enter 0 for your email server, or accept the default value. After creating MX record, you also need to create an A record for mail.your-domain.com , so that it can be resolved to an IP address. If your server uses IPv6 address, be sure to add AAAA record.

Hint: If you use Cloudflare DNS service, you should not enable the CDN feature when creating A record for your mail server. Cloudflare does not support SMTP proxy.

Step 3: Configuring Hostname

Log into your server via SSH, then run the following command to update existing software packages.

sudo apt update

sudo apt upgrade

And set a fully qualified domain name (FQDN) for your server with the following command.

sudo hostnamectl set-hostname mail.your-domain.com

We also need to update /etc/hosts file.

sudo nano /etc/hosts

Edit it like below:

127.0.0.1       mail.your-domain.com localhost

Save and close the file. To see the changes, re-login and then run the following command to see your hostname.

hostname -f

Step 4: Setting up Mail Server on Ubuntu 18.04 with iRedMail

Run the following command download the iRedMail Bash installer with wget. At the time of this writing, the latest version of iRedMail is 0.9.8, released on April 3, 2018. Please go to iRedMail download page  to check out the latest version.

wget https://bitbucket.org/zhb/iredmail/downloads/iRedMail-0.9.8.tar.bz2

You can always use the above URL format to download the latest version. Just replace 0.9.8 with the new version number.

Extract the tarball.

tar xvf iRedMail-0.9.8.tar.bz2

Then cd into the newly created directory.

cd iRedMail-0.9.8/

Add executable permission to the iRedMail.sh script.

chmod  x iRedMail.sh

Next, run the Bash script with sudo privilege.

sudo bash iRedMail.sh

The ncurse-based setup wizard will appear. Select Yes and press Enter.

The next screen will ask you to select the mail storage path. You can use the default one /var/vmail, so simply press Enter.

Then choose whether you want to run a web server. It’s highly recommended that you choose to run a web server because you need the web-based admin penal to add email accounts. Also it allows you to access the Roundcube webmail. By default, Nginx web server is selected, so you can simply press Enter.  (An asterisk indicates the item is selected.)

Then select the storage backend. Choose one that you are familiar with. This tutorial chose MariaDB. Press up and down arrow key and press the space bar to select.

If you selected MariaDB or MySQL, then you will need to set the MySQL root password.

Note that if you selected MariaDB, then you don’t need password to log into MariaDB shell. Instead of running the normal command mysql -u root -p, you can run the following command to login, with sudo and without providing MariaDB root password.

sudo mysql -u root

This is because the MariaDB package on Ubuntu 18.04 uses unix_socket authentication plugin, which allows users to use OS credentials to connect to MariaDB, but you still need to set root password in iRedMail setup wizard.

Next, enter your first mail domain. You can add additional mail domains later in the web-based admin panel. This tutorial assumes that you want an email account like [email protected], in that case, you need to enter your-domain.com here, without sub-domain. Do not press the space bar after your domain name. I think iRedMail will copy the space character along with your domain name, which can result in installation failure.

Next, set a password for the mail domain administrator.

Choose optional components. By default, 4 items are selected. If you like to have SOGo groupware, then select it and press Enter.

Now you can review your configurations. Type Y to begin the installation of all mail server components.

At the end of installation, choose y to use firewall rules provided by iRedMail and restart firewall.

Now iRedMail installation is complete. You will be notified the URL of webmail, SOGo groupware and web admin panel and the login credentials. The iRedMail.tips file contains important information about your iRedMail server.

Reboot your Ubuntu 18.04 server.

sudo shutdown -r now

Once your server is back online, you can visit the web admin panel.

https://mail.your-domain.com/iredadmin/

Note that in the above URL, the sub-directory for accessing the admin panel is /iredadmin/, not /iredmail/. And because it’s using a self-signed TLS certificate, you need to add security exception.

Step 5: Installing Let’s Encrypt TLS Certificate

Since the mail server is using a self-signed TLS certificate, both desktop mail client users and webmail client users will see a warning. To fix this, we can obtain and install a free Let’s Encrypt TLS certificate.

Obtaining the Certificate

First, install Let’s Encrypt (certbot) client on Ubuntu 18.04

sudo apt install software-properties-common
sudo add-apt-repository ppa:certbot/certbot
sudo apt install certbot

iRedMail has already configured TLS settings in the default Nginx virtual host, so here I recommend using the webroot plugin, instead of nginx plugin, to obtain certificate. Run the following command. Replace red text with your actual data.

sudo certbot certonly --webroot --agree-tos --email your-email-address -d mail.your-domain.com -w /var/www/html/

When it asks you if you want to receive communications from EFF, you can choose No.

If everything went well, you will see the following text indicating that you have successfully obtained a TLS certificate. Your certificate and chain have been saved at /etc/letsencrypt/live/mail.your-domain.com/ directory.

If certbot failed to obtain TLS certificate, maybe it’s because your DNS records are not propagated to the Internet. Depending on the domain registrar you use, your DNS record might be propagated instantly, or it might take up to 24 hours to propagate. You can go to https://dnsmap.io, enter your mail server’s hostname (mail.your-domain.com) to check DNS propagation.

Note that sometimes, the self-signed certificate can prevent Let’s Encrypt ACME server from connecting to your server and the certificate won’t be issued. You can disable HTTPS on the default virtual host to fix this problem, then re-enable HTTPS after a valid Let’s Encrypt certificate is obtained.

Installing the Certificate in Nginx

After obtaining a TLS certificate, let’s configure Nginx web server to use it. Edit the SSL template file.

sudo nano /etc/nginx/templates/ssl.tmpl

Find the following 2 lines.

ssl_certificate /etc/ssl/certs/iRedMail.crt;
ssl_certificate_key /etc/ssl/private/iRedMail.key;

Replace them with:

ssl_certificate /etc/letsencrypt/live/mail.your-domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mail.your-domain.com/privkey.pem;

Save and close the file. Then test nginx configuration and reload.

sudo nginx -t

sudo systemctl reload nginx

Visit iRedMail admin panel again, your web browser won’t warn you any more because Nginx is now using a valid TLS certificate.

Installing TLS Certificate in Postfix and Dovecot

We also need to configure Postfix SMTP server and Dovecot IMAP server to use the Let’s Encrypt issued certificate so that desktop mail client won’t display security warning. Edit the main configuration file of Postfix.

sudo nano /etc/postfix/main.cf

Find the following 3 lines. (line 95, 96, 97).

smtpd_tls_key_file = /etc/ssl/private/iRedMail.key
smtpd_tls_cert_file = /etc/ssl/certs/iRedMail.crt
smtpd_tls_CAfile = /etc/ssl/certs/iRedMail.crt

Replace them with:

smtpd_tls_key_file = /etc/letsencrypt/live/mail.your-domain.com/privkey.pem
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.your-domain.com/cert.pem
smtpd_tls_CAfile = /etc/letsencrypt/live/mail.your-domain.com/chain.pem

Save and close the file. Then reload Postfix.

sudo systemctl reload postfix

Next, edit the main configuration file of Dovecot.

sudo nano /etc/dovecot/dovecot.conf

Fine the following 2 lines. (line 47, 48)

ssl_cert = 

Replace them with:

ssl_cert = mail.your-domain.com/fullchain.pem
ssl_key = mail.your-domain.com/privkey.pem

Save and close the file. Then reload dovecot.

sudo systemctl reload dovecot

From now on, desktop mail users won’t see security warnings.

Step 6: Sending Test Email

Log into iredadmin panel with the postmaster mail account. In the Add tab, you can add additional domains or email addresses.

If you see “no domain under control” error, please refer to this article.

After you create a user, you can visit the Roundcube webmail address and login with the new mail user account.

https://mail.your-domain.com/mail/

Now you can test email sending and receiving. Please note that you may need to wait a few minutes to receive emails because iRedMail by default enables greylisting, which is a way to tell other sending SMTP servers to try again in a few minutes. The following line in mail log file /var/log/mail.log indicates greylisting is enabled.

Recipient address rejected: Intentional policy rejection, please try again later;

Step 7: Checking If Port 25 (outbound) is blocked

Your ISP or hosting provider won’t block incoming connection to port 25 of your server, which means you can receive emails from other mail servers. However, many ISP/hosting providers block outgoing connection to port 25 of other mail servers, which means you can’t send emails.

If your email didn’t arrive at your other email address such as Gmail, then run the following command on your mail server to check if port 25 (outbound) is blocked.

telnet gmail-smtp-in.l.google.com 25

If it’s not blocked, you would see messages like below, which indicates a connection is successfully established. (Hint: Type in quit and press Enter to close the connection.)

Trying 74.125.68.26...
Connected to gmail-smtp-in.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP y22si1641751pll.208 - gsmtp

If port 25 (outbound) is blocked, you would see something like:

Trying 2607:f8b0:400e:c06::1a...
Trying 74.125.195.27...
telnet: Unable to connect to remote host: Connection timed out

In this case, your Postfix can’t send emails to other SMTP servers. Ask your ISP/hosting provider to open it for you. If they refuse your request, you need to set up SMTP relay to bypass port 25 blocking.

Step 8: Using Mail Clients on Your Computer or Mobile Device

Fire up your desktop email client such as Mozilla Thunderbird and add a mail account.

  • In the incoming server section, select IMAP protocol, enter mail.your-domain.com as the server name, choose port 993 and SSL/TLS. Choose normal password as the authentication method.
  • In the outgoing section, select SMTP protocol, enter mail.your-domain.com as the server name, choose port 587 and STARTTLS. Choose normal password as the authentication method.

Step 9: Improving Email Deliverablity

To prevent your emails from being flagged as spam, you should set PTR, SPF, DKIM and DMARC records.

PTR record

A pointer record, or PTR record, maps an IP address to a FQDN (fully qualified domain name). It’s the counterpart to the A record and is used for reverse DNS lookup, which can help with blocking spammers. Many SMTP servers reject emails if no PTR record is found for the sending server.

To check the PTR record for an IP address, run this command:

dig -x IP-address  short

or

host IP-address

Because you get IP address from your hosting provider or ISP, not from your domain registrar, so you must set PTR record for your IP in the control panel of your hosting provider, or ask your ISP.  Its value should be your mail server’s hostname: mail.your-domain.com. If your server uses IPv6 address, be sure to add a PTR record for your IPv6 address as well.

To edit the reverse DNS record for your Hostwinds VPS, log into Hostwinds client area, select Domains -> Manage rDNS, Then you can edit the reverse DNS record for both IPv4 and IPv6 address.

SPF Record

SPF (Sender Policy Framework) record specifies which hosts or IP address are allowed to send emails on behalf of a domain. You should allow only your own email server or your ISP’s server to send emails for your domain. In your DNS management interface, create a new TXT record like below.

Explanation:

  • TXT indicates this is a TXT record.
  • Enter @ in the name field to represent the main domain name.
  • v=spf1 indicates this is a SPF record and the version is SPF1.
  • mx means all hosts listed in the MX records are allowed to send emails for your domain and all other hosts are disallowed.
  • ~all indicates that emails from your domain should only come from hosts specified in the SPF record. Emails that are from other hosts will be flagged as forged.

To check if your SPF record is propagated to the public Internet, you can use the dig utility on your Linux machine like below:

dig your-domain.com txt

The txt option tells dig that we only want to query TXT records.

DKIM Record

DKIM (DomainKeys Identified Mail) uses a private key to digitally sign emails sent from your domain. Receiving SMTP servers verify the signature by using the public key, which is published in the DNS DKIM record.

The iRedMail script automatically configured DKIM for your server. The only thing left to do is creating DKIM record in DNS manager. Open the iRedMail.tips file under iRedMail-0.9.8 directory.

sudo nano iRedMail.tips

Scroll down to DNS record for DKIM support section. The DKIM public key is in the parentheses.

You can also show the public key with the following command.

sudo amavisd-new showkeys

Then in your DNS manager, create a TXT record, enter dkim._domainkey in the name field. Copy everything in the parentheses and paste into the value field. Delete all double quotes.

After saving your changes, run the following command to test if your DKIM record is correct.

sudo amavisd-new testkeys

If the DKIM record is correct, the test will pass. Note that your DNS record may need sometime to propagate to the Internet.

TESTING#1 linuxbabe.com: dkim._domainkey.linuxbabe.com => pass

DMARC Record

DMARC stands for Domain-based Message Authentication, Reporting and Conformance. DMARC can help receiving email servers to identify legitimate emails and prevent your domain name from being used by email spoofing.

To create a DMARC record, go to your DNS manager and add a TXT record. In the name field, enter _dmarc. In the value field, enter the following:

v=DMARC1; p=none; pct=100; rua=mailto:[email protected]

The above DMARC record is a safe starting point. To see the full explanation of DMARC, please check the following article.

Step 10: Testing Email Score and Placement

After creating PTR, SPF, DKIM record, go to https://www.mail-tester.com. You will see a unique email address. Send an email from your domain to this address and then check your score. As you can see, I got a perfect score. In the test result, you should check if your PTR record, SPF and DKIM record is valid.

Mail-tester.com can only show you a sender score. There’s a another service called GlockApps that allow you to check if your email is landed in the recipient’s inbox or spam folder, or rejected outright. It supports many popular email providers like Gmail, Outlook, Hotmail, YahooMail, iCloud mail, etc

What if Your Emails Are Still Being Marked as Spam?

I have more tips for you in this article: How to stop your emails being marked as spam. Although it will take some time and effort, your emails will eventually be placed in inbox after applying these tips.

What if Your Email is Rejected by Microsoft Mailbox?

Microsoft seems to be using an internal blacklist that blocks many legitimate IP addresses. If your emails are rejected by Outlook or Hotmail, you need to submit the sender information form. After that, your email will be accepted by Outlook/Hotmail.

Adding Multiple Mail Domains

I wrote this article to show you how to add multiple mail domains in iRedMail.

How to Disable Greylisting

By default, iRedMail has enabled greylisting, which tells other sending SMTP servers to try again in a few minutes. This is mainly useful to block spam, but it also degrades user experience. If you prefer to disable greylisting, follow the instructions below.

Add write permission to the /opt/iredapd/settings.py file.

sudo chmod 600 /opt/iredapd/settings.py

Then edit the configuration file.

sudo nano /opt/iredapd/settings.py

Find the following line.

plugins = ["reject_null_sender", "wblist_rdns", "reject_sender_login_mismatch", "greylisting", "throttle", "amavisd_wblist", "sql_alias_access_policy"]

Remove "greylisting" from the list. Save and close the file. Then restart iredapd.

sudo systemctl restart iredapd

Change the configuration file back to read only mode.

sudo chmod 400 /opt/iredapd/settings.py

Enabling SMTPS Port 465

If you are going to use Microsoft Outlook client, then you need to enable SMTPS port 465 in Postfix SMTP server.

Troubleshooting

First, please use a VPS with at least 2GB RAM. Running iRedMail on a 1GB RAM VPS will cause the database, SpamAssassin, or ClamAV to be killed because of out-of-memory problem. If you really want to use a 1GB RAM VPS, you are going to lose incoming emails and have other undesirable outcomes.

If the iRedMail web interface isn’t accessible, like a 502 gateway error, you should check the Nginx logs in /var/log/nginx/ directory to find clues. You may also want to check the mail log /var/log/mail.log.

Check if the various services are running.

systemctl status postfix

systemctl status dovecot

systemctl status nginx

systemctl status mariadb

systemctl status clamav-daemon

systemctl status amavis

If you enabled the firewall, you should open the following ports in the firewall.

HTTP port:  80
HTTPS port: 443
SMTP port:  25
Submission port: 587 (and 465 if you are going to use Microsoft Outlook mail client)
IMAP port:  143 and 993

If you would like to use the UFW firewall, check my guide here: Getting started with UFW firewall on Debian and Ubuntu.

How to Renew TLS Certificate

Let’s Encrypt issued TLS certificate is valid for 90 days only and it’s important that you set up a Cron job to automatically renew the certificate. You can run the following command to renew certificate.

sudo certbot renew

You can use the --dry-run option to test the renewal process, instead of doing a real renewal.

sudo certbot renew --dry-run

Error #1

If you see the following error when renewing TLS certificate:

The server could not connect to the client to verify the domain. Timeout during connect (likely firewall problem). Skipping.

This is mostly because you didn’t add AAAA record for mail.yourdomain.com, so create AAAA record in your DNS manager. You also need to enable IPv6 in Nginx virtual host. Edit the /etc/nginx/sites-enabled/000-default.conf file and find the following line.

#listen [::]:80;

Remove the # symbol to enable IPv6.

listen [::]:80;

Save and close the file. Then edit the SSL virtual host /etc/nginx/sites-enabled/00-default-ssl.conf. Add the following line.

listen [::]:443 ssl http2;

Save and close the file. Then test Nginx configuration.

sudo nginx -t

If the test is successful, reload Nginx for the change to take effect.

sudo systemctl reload nginx

Error #2

If you see the following error when renewing TLS certificate.

The client lacks sufficient authorization :: Invalid response

Then you need to create the hidden directory.

sudo mkdir -p /var/www/html/.well-known/acme-challenge

And set www-data as the owner of the webroot.

sudo chown www-data:www-data /var/www/html/ -R

Also, edit the SSL virtual host /etc/nginx/sites-enabled/00-default-ssl.conf. Add the following lines.

location ~ /.well-known/acme-challenge {
     root /var/www/html/;
     allow all;
}

Save and close the file. Test Nginx configuration and reload.

sudo nginx -t
sudo systemctl reload nginx

Create Cron Job

If now the dry run is successful, you can create Cron job to automatically renew certificate. Simply open root user’s crontab file.

sudo crontab -e

Then add the following line at the bottom of the file.

@daily certbot renew --quiet && systemctl reload postfix dovecot nginx

Reloading Postfix, Dovecot and Nginx is necessary to make these programs pick up the new certificate and private key.

Setting Up Backup Mail Server

Your primary mail server could be down sometimes. If you host your mail server in a data center, then the downtime is very minimal, so you shouldn’t be worried about losing inbound emails. If you host your mail server at home, the downtime can’t be predicted so it’s a good practice for you to run a backup mail server in a data center to prevent losing inbound emails. The backup mail server needs just 512MB RAM to run. Please check the full detail in the following article.

For Advanced Users

iRedMail doesn’t include a DMARC verification service, you can check out the following tutorial to set up OpenDMARC to block email spoofing.

You may want to customize the SpamAssassin content filter to better detect spam.

If your website and mail server are running on two different VPS (virtual private server), you can set up SMTP relay between your website and mail server, so that your website can send emails through your mail server. See the following article.

Wrapping Up

That’s it! I hope this tutorial helped you set up a mail server on Ubuntu 18.04 with iRedMail. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial

[Total: 27 Average: 4.7]