How to Easily Set Up a Full-Featured Mail Server on CentOS 7 with iRedMail

Setting up your own email server on Linux from scratch is a long and tedious process, 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 CentOS 7, saving you lots of time and headaches.

What is iRedMail?

iRedMail is a shell script that automatically installs and configures 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, PostgreSQL database, or OpenLDAP. The following is a list of open-source software that will be automatically installed and configured by iRedMail.

  • Postfix SMTP server
  • Dovecot IMAP server
  • Nginx web server to serve the admin panel and webmail
  • OpenLDAP, MySQL/MariaDB, or PostgreSQL for storing user information
  • Amavised-new for DKIM signing and verification
  • SpamAssassin for anti-spam
  • ClamAV for anti-virus
  • Roundcube webmail
  • Fail2ban for protecting SSH
  • 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 full-featured email server with iRedMail, you need a server with at least 3GB RAM, because after the installation, your server will use more than 2GB of RAM.

It is highly recommended that you install iRedMail on a clean install of CentOS 7 server.

This tutorial is done on a $9/month Kamatera VPS (virtual private server) with 1 CPU and 3GB RAM. They offer a 30-day free trial.

Kamatera is a very good option to run a mail server because

  • They don’t block port 25, so you can send unlimited emails (transactional email and newsletters) without spending money on SMTP relay service. Kamatera doesn’t have any SMTP limits. You can send a million emails per day.
  • The IP address isn’t on any email blacklist. (At least this is true in my case. I chose the Dallas data center.) You definitely don’t want to be listed on the dreaded Microsoft Outlook IP blacklist or the spamrats blacklist. Some blacklists block an entire IP range and you have no way to delist your IP address from this kind of blacklist.
  • You can edit PTR record to improve email deliverability.
  • They allow you to send newsletters to your email subscribers with no hourly limits or daily limits, whatsoever.
  • You can order multiple IP addresses for a single server. This is very useful for folks who need to send a large volume of emails. You can spread email traffic on multiple IP addresses to achieve better email deliverability.

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 Kamatera website to create an account, then create your server in your account dashboard.

kamatera server types

I recommend following the tutorial linked below to properly set up your Linux VPS server on Kamatera.

Once you created a server, Kamatera 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.

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.

iredmail email server create MX record

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. It’s recommended that you set the value to 0, so this mail server will have the highest priority for receiving emails. 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 mail.your-domain.com. 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 yum update -y

I strongly recommend creating a sudo user for managing your server rather than using the default root user to improve server security. Run the following command to create a user. Replace username with your preferred username.

sudo adduser username

Set a password for this user.

sudo passwd username

Add this user to the wheel group in order to use sudo.

sudo gpasswd -a username wheel

Switch to the new user.

su - username

Next, 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 with a command-line text editor like Nano.

sudo nano /etc/hosts

Edit it like below. (Use arrow keys to move the cursor in the file.)

127.0.0.1       mail.your-domain.com localhost

Save and close the file. (To save a file in Nano text editor, press Ctrl+O, then press Enter to confirm. To close the file, press Ctrl+X.)

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

hostname -f

Step 4: Setting up Mail Server on CentOS 7 with iRedMail

Run the following commands to download the latest version of iRedMail script installer from its Github repository.

sudo dnf install wget tar -y
wget https://github.com/iredmail/iRedMail/archive/1.5.1.tar.gz

Extract the archived file.

tar xvf 1.5.1.tar.gz

Then cd into the newly-created directory.

cd iRedMail-1.5.1/

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 mail server setup wizard will appear. Use the Tab key to select Yes and press Enter.

centos-7-iredmail-server

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

centos-7-iredmail-default-storage-path

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 panel 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.)

centos-7-iredmail-nginx-web-server

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

centos-7-email-server

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

centos-7-mail-server

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.

set-up-mail-server-on-centos-7

Next, set a password for the mail domain administrator.

centos-7-email-server-step-by-step

Choose optional components. By default, all of the 4 items are selected. So simply press Enter.

centos-7-iredmail-optional-components

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

centos-7-iredmail-review-config

Make sure you see no error in the installation process. If there are errors, it’s better to reinstall the OS and then reinstall iRedMail on your server, or your mail server might not work properly.

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

centos-7-iredmail-firewall-rules-mysql-config

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

iredmail url of installed web applications

Reboot your CentOS 7 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 in your web browser.

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, log into your server again via SSH and run the following commands to install Let’s Encrypt (certbot) client on CentOS 7.

sudo yum install certbot python-certbot-nginx -y

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 the certificate. Run the following command. Replace with the red text with your own email address and hostname.

sudo certbot certonly --webroot --agree-tos --email [email protected] -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.

iredmail-letsencrypt-certbot

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.

iredmail tls certificate

Failure to Obtain TLS Certificate

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.

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/pki/tls/certs/iRedMail.crt;
ssl_certificate_key /etc/pki/tls/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.

iredadmin

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/pki/tls/private/iRedMail.key
smtpd_tls_cert_file = /etc/pki/tls/certs/iRedMail.crt
smtpd_tls_CAfile = /etc/pki/tls/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 = </etc/pki/tls/certs/iRedMail.crt
ssl_key = </etc/pki/tls/private/iRedMail.key

Replace them with:

ssl_cert = </etc/letsencrypt/live/mail.your-domain.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/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 ([email protected]). In the Add tab, you can add additional domains or email addresses.

add email addresses in iredadmin

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/

iredmail roundcube webmail

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 the mail log file /var/log/maillog indicates greylisting is enabled.

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

Checking if ClamAV is Running

ClamAV is used to scan viruses in email messages. ClamAV can use a fair amount of RAM. If there’s not enough RAM on your server, ClamAV won’t work properly, which will prevent your mail server from sending emails. You can check its status with:

systemctl status clamd@amavisd

If your ClamAV is always activating like below, you have a problem.

systemctl status clamd@amavisd

Check ClamAV logs.

sudo journalctl -eu clamd@amavisd

If you see the following line in the logs, that means your server doesn’t have enough RAM to run ClamAV.

daemonize() failed: Cannot allocate memory

You can add a swap file to your server to increase the total RAM on your server. (Note that using swap space on the server can greatly degrade server performance. If you want better performance, you should upgrade the physical RAM instead of using swap space.)

To add swap space on the server, first, use the fallocate command to create a file. For example, create a file named swapfile with 1G capacity in root file system:

sudo fallocate -l 1G /swapfile

Then make sure only root can read and write to it.

sudo chmod 600 /swapfile

Format it to swap:

sudo mkswap /swapfile

Output:

Setting up swapspace version 1, size = 2014 MiB (536866816 bytes)
no label, UUID=0aab5886-4dfb-40d4-920d-fb1115c67433

Enable the swap file

sudo swapon /swapfile

Wait a few seconds, your ClamAV should be active (running), and it won’t prevent your mail server from sending emails.

systemctl status clamd@amavisd

clamav memory usage

To mount the swap space at system boot time, edit the /etc/fstab file.

sudo nano /etc/fstab

Add the following line at the bottom of this file.

/swapfile    swap    swap     defaults    0   0

Save and close the file. Then reload systemd.

sudo systemctl daemon-reload

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 you can use the telnet utility to check if port 25 (outbound) is blocked. Install telnet on CentOS 7 with:

sudo yum install telnet

Then run the following command on your mail server.

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

If port 25 (outbound) is 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.

Still Can’t Send Email?

If port 25 (outbound) is not blocked, but you still can’t send emails from your own mail server to your other email address like Gmail, then you should check the mail log (/var/log/mail.log).

sudo nano /var/log/mail.log

For example, some folks might see the following lines in the file.

host gmail-smtp-in.l.google.com[2404:6800:4003:c03::1b] said: 550-5.7.1 [2a0d:7c40:3000:b8b::2] Our system has detected that 550-5.7.1 this message does not meet IPv6 sending guidelines regarding PTR 550-5.7.1 records and authentication. Please review 550-5.7.1 https://support.google.com/mail/?p=IPv6AuthError for more information

This means your mail server is using IPv6 to send the email, but you didn’t set up IPv6 records. You should go to your DNS manager, set AAAA record for mail.your-domain.com, then you should set PTR record for your IPv6 address, which is discussed in step 9.

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

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. If Thunderbird found your mail server configuration like below, simply click Done button and you will be able to read and send emails.

mozilla thunderbird set up an existing email account

If Thunderbird didn’t found your mail server configuration, then click Manual config button to enter your mail server details.

  • In the incoming server section, select IMAP protocol, enter mail.your-domain.com as the server name, choose port 143 and STARTTLS. 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.

ubuntu postfix dovecot letsencrypt https

Hint: You can also use IMAP on port 993 with SSL/TLS encryption.

Fail2ban Blocking Your Own IP Address

If you made a mistake and failed to log in to mail server multiple times, then the Fail2ban service on the mail server might block your IP address. You can add your IP address to whitelist by editing the jail.local file.

sudo nano /etc/fail2ban/jail.local

Add your own IP address to the ignore list like below. Replace 12.34.56.78 with your real IP address.

ignoreip = 12.34.56.78 127.0.0.1 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16

Save and close the file. Then restart Fail2ban.

sudo systemctl restart fail2ban

Step 9: Improving Email Deliverability

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 an 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

PTR record isn’t managed by your domain registrar. It’s managed by the person who gives you an IP address. Because you get IP address from your hosting provider or ISP, not from your domain registrar, 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 Kamatera VPS, log into the Kamatera client area, then open a support ticket and tell them to add PTR record for your server IP addresss to point the IP address to mail.your-domain.com. It’s not convenient, you might think, but this is to keep spammers away from the platform, so legitimate email senders like us will have a great IP reputation.

SPF Record

SPF (Sender Policy Framework) record specifies which hosts or IP addresses 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.

mail server spf record

Where:

  • 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. Run the following command to show the DKIM public key.

sudo amavisd -c /etc/amavisd/amavisd.conf showkeys

The DKIM public key is in the parentheses.

iredmail-amavis-dkim-key

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 and line breaks.

amavisd-new ubuntu

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

sudo amavisd -c /etc/amavisd/amavisd.conf testkeys

If the DKIM record is correct, the test will pass.

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

Note that your DKIM record may need sometime to propagate 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://www.dmarcanalyzer.com/dkim/dkim-check/, enter dkim as the selector and enter your domain name to check DKIM record propagation.

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. (You should create the [email protected] email address.)

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

create dmarc record txt

The above DMARC record is a safe starting point. If you want to read the full explanation of DMARC, please check the following article. Note that this is optional.

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.

Testing Email Score and PlacementMail-tester.com can only show you a sender score. There’s 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.

glockapps-email-placement-test-scalahosting-vps

Email is Rejected by Microsoft Mailbox?

Microsoft uses an internal blacklist that blocks many legitimate IP addresses. If your emails are rejected by Outlook or Hotmail, you need to follow the tutorial linked below to bypass Microsoft Outlook blacklist.

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.

Adding Multiple Mail Domains

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

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 4GB 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/maillog.

Check if the various services are running.

systemctl status postfix

systemctl status dovecot

systemctl status nginx

systemctl status mariadb

systemctl status clamd@amavisd

systemctl status amavisd

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 -w /var/www/html

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

sudo certbot renew -w /var/www/html --dry-run

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;
}

iredmail letsencrypt renew

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 -w /var/www/html/ --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.

For Advanced Users

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 CentOS 7 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: 0 Average: 0]

41 Responses to “How to Easily Set Up a Full-Featured Mail Server on CentOS 7 with iRedMail

  • Dear Xiao Guoan

    Thank you so much for your tutorials. that very helpful

  • landryjohn
    3 years ago

    Thank you Xiao Guoan.
    I will try it in the morning on our online cloud server.

    I was following one of your articles about configuration with moboboa. But in the comments, for the sake of stability you recommended iRedMail. Does this mean that iRedMail is the best choice for stability ? Or depending on the version of moboboa we use it can be better? and what do you think of mail-in-box? Thanks again to you

    • Xiao Guoan (Admin)
      3 years ago

      iRedMail is maintained by a team of full-time developers. Modoboa is one person’s part time project. So naturally, iRedMail is more stable than Modoboa, and problems are solved much faster by the developers.

      As far as I know, mail-in-a-box doesn’t allow custom configuration from the command line. It’s suitable for average users who don’t need customization.

  • Morning to all.
    Please i need your help. I tried to load the installation process of iRedMail via bash iRedMail.sh. After choosing the different settings. The installation stop with this error :
    Error: Package: python36-sqlalchemy-1.1.3-3.el7.x86_64 (epel)
    Requires: python(abi) = 3.6

  • <preHint: If you use Cloudflare DNS service, you should not enable the CDN feature when creating A record for mail.your-domain.com. Cloudflare does not support SMTP proxy.

    Is there any solution for this ?
    I use CDN feature already in cloudflare (AWS static content) , Please help i cant access : https://mail.XXXX.XXX/iredadmin/ after setup, i am stuck

  • Thanks fro reply, will try that, But everytime i update anything related to email service that need disable of cloudflare proxy ? No other way around ? I will check how to do that, not sure right now.

    • Xiao Guoan (Admin)
      3 years ago

      You need to disable Cloudflare proxy for the hostname of your mail server permanently, otherwise you won’t be able to receive emails, because Cloudflare doesn’t support SMTP and IMAP proxy. There’s no way around.

      To disable Cloudflare for a hostname, click the orange cloud icon under the Proxy status column in the DNS dashboard. Then another orange cloud icon will appear. Click on it, the status will change to DNS only. Save the setting, and you are done.

  • Sébastien
    3 years ago

    Hello,

    thank you for this wonderful tutorial that I followed a few months ago to install Iredmail as a mail server for several domains on an “A” server (running under Centos7).

    Today, on the one hand, I would like to migrate my mail server from server “A” to my new server “B” which works with Centos8. Can you tell me what procedure I must follow in order to carry out this transfer while keeping the existing mails in the different mailboxes of the different domains? please thank you

    On the other hand, I would like to set up a backup system allowing me to alleviate a possible server problem. Which folders and files should I back up regularly and how? please thank you.
    Can toi make Caron tâche for this backup système ?

    In addition, does a change of server (but not of domains installed in Iredmail) require a change of SSL certificate? please thank you If yes, how to make this change? please thank you

    To conclude, how to set up aliases in Iredmail? please thank you

    cordially

    Sebastian

  • David Montellano
    3 years ago

    This tutorial es very helpful. Now my iredmail is working 🙂

  • William Fourche
    3 years ago

    Hello,

    To put your tutorials into practice, I am currently using a web server under Centos. Following the announcement of the “death” of Centos (Centos7 being maintained until June 2024 while Centos8 is until 2021), I wanted to know if you can advise me another distribution presenting the main advantages of Centos (long maintenance time, stability, security and large community) for a Lan server or a Wan server? please thank you

    Kind regards,
    William

    • Xiao Guoan (Admin)
      3 years ago

      There are two options that are the most promising:
      1.) Rocky Linux. This community project is created by one of the original founders of CentOS.
      2.) CloudLinux, which provides software support for hosting companies, is expecting to release its own rebuilt of RHEL in the first quarter of 2021.

  • Ired mail installed succesfully, however,

    After this step Reboot your CentOS 7 server.

    sudo shutdown -r now

    My Nginx on centOs7 server on digitalocean is now down.
    I tried sudo reboot -h now command but putty immediately becomes inactive with an error about remote connection.

    Also, when i try to visit either iredmail admin url or my website, I get an ERR_CONNECTION_REFUSED in browser.

    Please what is the best way to resolve this?

    Thank you.

    • Xiao Guoan (Admin)
      3 years ago

      Increase server RAM.

      • My server RAM is 2GB.

        I run this command sudo service nginx start and now I am able to access the site, however, https://mydomain.com( which has let’s encrypt ssl installed) is now redirecting to mydomain.com/mail with https cancelled and a 502 Bad Gateway
        displaying in the browser.

        Also mariadb is Inactive (dead) when I run systemctl status mariadb , even when i try this systemctl enable mariadb , I get an error Unit mariadb.service cannot be found.

    • Xiao Guoan (Admin)
      3 years ago

      Iredmail should be installed on a clean fresh server.

      • can the server be different from the server that’s currently hosting my domain?
        Also, how can I safely uninstall or undo iredmail to get my previous server settings..?
        Thank you…

    • Xiao Guoan (Admin)
      3 years ago

      Yes. The mail server and the website can run on two different hosts.

      You can use the snapshot feature in your hosting provider to roll back your server to a previous state.

      • Thank you Xiao, I don’t remember creating a snapshot.
        Is there another way I could restore to working version as of yesterday?
        Thank you.

  • I created a new centos 7 server on vultr and have successfully installed Iredmail, however, I think I need help with linking subdomain to vultr.

    Currently, I am able to access iredmail through https://my ip for vultr/iredadmin.

    At the site where I purchased my domain, I have created a subdomain there named mail.mydomain.com.
    For that subdomain, I have changed the ip for type A value to my ip for vultr.
    I have also changed type MX value to ns1.vultr.com.

    At the vultr host where the email is hosted, I have added mymaindomain.com.
    Under it, the ip for type A value to my ip for vultr.
    type CNAME value to mymaindomain.com
    type MX value to mail.mydomain.com
    type NS value to ns1.vultr.com
    type NS value to ns2.vultr.com
    I have also changed type MX value to ns1.vultr.com.

    Please let me know if I made an error in DNS settings.
    Thank you.

    • Thank you, I got it figured out by following this link https://www.digitalocean.com/community/questions/how-can-i-point-a-subdomain-to-a-different-host.

      Thank you for your amazing tutorial.

      • At step 6: when I run this systemctl status clamd@amavisd , I get Failed error. In the error, I see the following:

        No supported database files found in /var/lib/cl
        Failed tro start clamscanner (amavids)
        Not loading PUA signatures

  • Cool Ferg
    2 years ago

    Hi, thanks to your tutorial, my email server is set up and running smoothly.
    I have one question though, do you think if I try to install modsecurity for nginx, the mail server will be destroyed, also is it necessary?

    • Xiao Guoan (Admin)
      2 years ago

      Modsecurity won’t destroy your mail server. However, you need to fiddle with the WAF rules, which is a very labour-intensive task.

      I only use ModSecurity to secure web applications that allow public access. For internal applications like a webmail, I prefer to use VPN to restrict access, which completely blocks random visitors from accessing the web application.

  • Cool Ferg
    2 years ago

    Thank you Xiao, my current mail server does not have enough space to install dig, it says cannot allocate memory…and since WAF rules route is labor intensive, is there another easier way to only restrict access to iredmail admin page and my mail.mydomain.com page to allow access only when i try to visit those urls from my home ip address range?

    for eg. for regular websites that uses apache, you can use the .htacess file to set allow from and deny….

    Thank you.

    • Xiao Guoan (Admin)
      2 years ago

      If your server is low on RAM and can not even install a simple piece of software, I highly recommend upgrading the RAM, or you risk losing inbound emais.

      • Cool Ferg
        2 years ago

        My server has 2048 MB of memory, is that good or too low?

    • Xiao Guoan (Admin)
      2 years ago

      2GB is a bare minimum for iRedMail. CentOS/RHEL uses more RAM than Debian/Ubuntu, so if you use CentOS/RHEL to run iRedMail, you need more RAM like 4GB.

      Many folks don’t want to spend more money on servers, and I understand. But think about it this way, you can have a self-hosted email server that also runs a newsletter application like Mautic, which is a free alternative to commercial email service providers like MailChimp, Aweber, etc. These commercial services can cost you hundreds of dollars per month.

      A self-hosted email server and Mautic can save you lots of money, so I won’t hesitate to spend a little extra money to upgrade the server.

      • Cool Ferg
        2 years ago

        Thank you Xiao, I will increase the memory and install Mautic as well.
        I have one quick question, do you have any tutorials on how to disable password authentication and use private key login through putty…I have nginx on Centos7.
        When i logged in using password, i saw that there’s been 88 failed logins on ssh notty…
        I tried a couple of tutorials on the web with using puttygen, but when i try to login the server denies connection and I get the errors in the links below and attached screenshot.
        https://ibb.co/p6TpvgV
        https://ibb.co/hBwHzC3

        Thank you.

    • Xiao Guoan (Admin)
      2 years ago

      You can set up SSH public key authentication on Windows within Powershell: How to Set Up SSH Key on Windows 10

  • Cool Ferg
    2 years ago

    I have been trying to set up smtp on my wordpress site to send emails using this plugin https://wordpress.org/plugins/post-smtp/#installation, however, even if i use the STARTTLS option with my roundcube/thunderbird email login credentials, I get the error below.

    SMTP Error: Could not connect to SMTP host.

    What is the best way to get smtp to work on wordpress?

    Thank you.

    • Xiao Guoan (Admin)
      2 years ago

      You can use the WP Mail SMTP plugin to send emails in WordPress.

      I also recommend enabling SMTPS in Postfix, so you can use the standard TLS if STARTTLS is not working.

      WordPress plugins might use different terms for SMTP submission.
      SSL: SMTPS on port 465
      TLS: STARTLS on port 587

      Make sure TCP port 587 and 465 are open on your server.

      sudo firewall-cmd --permanent --add-service={smtp-submission,smtps}
      sudo systemctl reload firewalld
      
      • Cool Ferg
        2 years ago

        I followed the steps including WP Mail SMTP plugin, enabling SMTPS in Postfix and the firewall commands, however I get the error below in WP Mail SMTP when I try to send a test email.

        Versions:
        WordPress: 5.8
        WordPress MS: No
        PHP: 7.4.20
        WP Mail SMTP: 2.9.0

        Params:
        Mailer: smtp
        Constants: No
        ErrorInfo: SMTP Error: Could not connect to SMTP host.
        Host: mail.mydomain.com
        Port: 587
        SMTPSecure: tls
        SMTPAutoTLS: bool(true)
        SMTPAuth: bool(true)

        Server:
        OpenSSL: OpenSSL 1.0.2k 26 Jan 2017

        Debug:
        Mailer: Other SMTP
        SMTP Error: Could not connect to SMTP host.

        SMTP Debug:

        2021-07-22 12:00:18 Connection: opening to mail.mydomain.com:587, timeout=300, options=array()

        2021-07-22 12:00:18 Connection: opened

        2021-07-22 12:00:18 SERVER -> CLIENT: 220 mail.mydomain.com ESMTP Postfix

        2021-07-22 12:00:18 CLIENT -> SERVER: EHLO mydomain.com

        2021-07-22 12:00:18 SERVER -> CLIENT: 250-mail.mydomain.com250-PIPELINING250-SIZE 15728640250-ETRN250-STARTTLS250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN

        2021-07-22 12:00:18 CLIENT -> SERVER: STARTTLS

        2021-07-22 12:00:18 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS

        2021-07-22 12:00:18 Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [/var/www/mydomain.com/html/wp-includes/PHPMailer/SMTP.php line 468]

        SMTP Error: Could not connect to SMTP host.

        2021-07-22 12:00:18 CLIENT -> SERVER: QUIT

        2021-07-22 12:00:18

        2021-07-22 12:00:18

        2021-07-22 12:00:18 Connection: closed

        SMTP Error: Could not connect to SMTP host.

    • Xiao Guoan (Admin)
      2 years ago

      You are using a self-signed TLS certificate, or your Let’s Encrypt certificate expired.

      • Cool Ferg
        2 years ago

        I am using Let’s Encrypt certificate and it is still valid. However, I noticed in phpinfo that openssl.capath and openssl.cafile has outputs of no value for both.
        My Let’s Encrypt certificate files (cert.pem,chain.pem,fullchain.pem,privkey.pem) are located at /etc/letsencrypt/live/mydomain.com/
        What is the best way for the certificate to be linked to openssl.capath and openssl.cafile ?

        Do you think that could solve the issue?

  • Elizabeth W Jones
    2 years ago

    bonsoir je reçois ce message après installation de iredmail centos 7 Transcript of session follow.

    Out: 220 mail.vbv-compte.cf ESMTP Postfix
    In: EHLO localhost
    Out: 250-mail.vbv-compte.cf
    Out: 250-PIPELINING
    Out: 250-SIZE 15728640
    Out: 250-ETRN
    Out: 250-STARTTLS
    Out: 250-ENHANCEDSTATUSCODES
    Out: 250-8BITMIME
    Out: 250 DSN
    In: STARTTLS
    Out: 454 4.7.0 TLS not available due to local problem
    In: QUIT
    Out: 221 2.0.0 Bye

    For other details, see the local mail logfile

    • Xiao Guoan (Admin)
      2 years ago

      “TLS not available due to local problem” This indicates you probably made a typo or syntax error when installing the TLS certificate in Postfix or Dovecot.

  • bytshop
    2 years ago

    Hello there ,
    Please can any one help me with dns i been faced some issues my domain provider is name.com ,
    I cannot find Name-Value , in my domain provider i have answer and host and i don’t know how to deal with it

    Thanks in advence

  • Just so say thanks for this comprehensive tutorial, great work!

  • thanks for the greak, tutorial.
    I installed it last year and its working fine. Recently seen the time mismatch while displaying mail view. After opening the mail, its showing proper date and time. any suggestions.

  • Amazing tutorial, thank you!
    WHen I reached the step to install iRedMail 1.5.1 on my CentOS 7 (2207) I received the error “Release version of the operating system on this server is unsupported by iRedMail” …

    Is there still a version which will work with CentOS 7 ? Any suggestions on the correct iRedMail / CentOS 7 combination? This is just for an internal mail server, and I’m not a fan of CentOS Stream.

    Thanks in advance.

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here