How to Setup a Mail Server on Ubuntu

A mail server empowers you with the capability to send and receive email directly. Opting for a self-hosted mail server on Ubuntu provides heightened control over your email infrastructure, enhancing both privacy and security. However, it’s important to acknowledge that managing your own mail server demands a certain level of technical expertise. This guide will walk you through how to setup a mail server on Ubuntu.
This comprehensive guide will walk you through all the steps to create a fully-functioning mail server on Ubuntu 20.04/22.04 from start to finish. Let’s delve into how to setup a mail server on Ubuntu.
Prerequisites
Before getting started, you’ll need the following:
- An Ubuntu 20.04/22.04 server
- A registered domain name
- A static IP address for your server
- Root access to the server
We’ll be using Postfix for the SMTP server, Dovecot for IMAP/POP3, and OpenDMARC for email authentication. A MySQL database will also be configured to store information like virtual domains and users.
Let’s start by updating the package repository and installing some dependencies on our Ubuntu server:
$ sudo apt update
$ sudo apt install postfix postfix-mysql dovecot-imapd dovecot-pop3d mariadb-server openssl openssl-blacklist
Next, we’ll go through the steps to configure each component.
Configuring Postfix
Postfix handles the SMTP service for sending and receiving emails. We need to update some settings in the main Postfix configuration file.
Open the file with:
$ sudo nano /etc/postfix/main.cf
Find the myhostname
parameter and set it to your registered domain name:
myhostname = mail.example.com
Next, find the mydomain
parameter and set it to your domain:
mydomain = example.com
Set the myorigin
parameter to $mydomain
:
myorigin = $mydomain
Under the INTERNET_PROTOCOLS
section, make sure ipv4
is enabled:
inet_interfaces = all
inet_protocols = all
This allows Postfix to listen on all available IPv4 network interfaces.
Now find the mydestination
parameter and set it to the following:
mydestination = $myhostname, localhost.$mydomain, $mydomain
This specifies the domains that Postfix will deliver mail to locally.
Save and close the file when you are done editing.
Next, we need to set up SMTP authentication. Generate a password file for Postfix with the postmap
command:
$ sudo postmap /etc/postfix/sasl_passwd
Create the user and password file:
$ sudo nano /etc/postfix/sasl_passwd
Add your email and password on separate lines:
mail.example.com <a href="/cdn-cgi/l/email-protection" data-cfemail="a8dddbcddac6c9c5cde8cdd0c9c5d8c4cd86cbc7c5">[email protected]</a>
mail.example.com password123
Save and close the file.
Now edit the Postfix SASL configuration:
$ sudo nano /etc/postfix/sasl/smtpd.conf
Make sure it has the following:
pwcheck_method: saslauthd
mech_list: plain login
This sets Postfix to use the saslauthd
service for authentication.
Restart Postfix to load the new configuration:
$ sudo systemctl restart postfix
Postfix is now configured and ready for sending and receiving emails.
Configuring Dovecot
Dovecot will be used to handle IMAP and POP3 protocols for accessing emails from mail clients like Outlook or Thunderbird.
Open the Dovecot configuration file:
$ sudo nano /etc/dovecot/dovecot.conf
Find the protocols section and enable imap and pop3:
protocols = imap pop3
Enable SMTP authentication:
disable_plaintext_auth = yes
Set the mail location:
mail_location = maildir:/var/mail/%d/%n
Now open the SMTP authentication config file:
$ sudo nano /etc/dovecot/conf.d/10-auth.conf
Find the auth_mechanisms
parameter and set it to:
auth_mechanisms = plain login
This allows plain text and login authentication similar to Postfix.
Finally, open the permissions file:
$ sudo nano /etc/dovecot/conf.d/10-mail.conf
And set:
mail_access_groups = mail
This allows members of the mail
group to access mailboxes.
Save and restart Dovecot:
$ sudo systemctl restart dovecot
Dovecot is now ready to handle IMAP and POP3 mail access.
MySQL Database Setup
Next, we’ll set up a MySQL database to store virtual domains and users for our mail server.
Log into the MySQL shell:
$ sudo mysql
Create a database called mailserver
:
CREATE DATABASE mailserver;
Create a new user and grant permissions on the database:
GRANT SELECT,INSERT,UPDATE,DELETE ON mailserver.* TO 'mailuser'@'127.0.0.1' IDENTIFIED BY 'password123';
Exit MySQL:
quit
Now we can import the Postfix configuration SQL file to create the necessary tables:
$ sudo mysql mailserver < /etc/postfix/mysql/postfix_db.sql
The MySQL database is now ready to store domain and user information for our mail server.
Virtual Domains and Users
With the database configured, we can create virtual domains and users.
A virtual domain allows you to host multiple domains from a single mail server.
First, open the Postfix virtual domain configuration file:
$ sudo nano /etc/postfix/mysql-virtual_domains.cf
Uncomment the config_directory parameter and set it to our MySQL config:
config_directory = /etc/postfix/mysql
Now let’s create a virtual domain entry in the database. Log into MySQL:
$ sudo mysql mailserver -p
Insert a row for the domain:
INSERT INTO `virtual_domains` (`id` ,`name`) VALUES ('1', 'example.com');
Exit MySQL.
Next, open the virtual users file:
$ sudo nano /etc/postfix/mysql-virtual_mailboxes.cf
Set the config_directory
like before:
config_directory = /etc/postfix/mysql
This allows Postfix to lookup users in MySQL.
Enter MySQL again:
$ sudo mysql mailserver -p
Create a sample user:
INSERT INTO `virtual_users` (`id`, `domain_id`, `password` , `email`) VALUES ('1', '1', ENCRYPT('password123', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), '<a href="/cdn-cgi/l/email-protection" data-cfemail="eb9e988e99858a868eab8e938a869b878ec5888486">[email protected]</a>');
This creates a user “[email protected]” with an encrypted password.
Now we need to allow the user to access mailboxes. Insert a row into virtual_aliases
:
INSERT INTO `virtual_aliases` (`id`, `domain_id`, `source`, `destination`) VALUES ('1', '1', '<a href="/cdn-cgi/l/email-protection" data-cfemail="5e2b2d3b2c303f333b1e3b263f332e323b703d3133">[email protected]</a>', '<a href="/cdn-cgi/l/email-protection" data-cfemail="661315031408070b0326031e070b160a034805090b">[email protected]</a>');
Exit MySQL and restart Postfix for the changes to take effect:
$ sudo systemctl restart postfix
We can create more domains and users in the same way.
OpenDMARC
OpenDMARC implements the DMARC email authentication standard. This helps improve security and prevent spam and phishing.
First, install OpenDMARC:
$ sudo apt install opendmarc opendmarc-tools
Open the main config file:
$ sudo nano /etc/opendmarc.conf
Set your domain:
AuthservID mail.example.com
Enable logging and reporting:
Socket inet:8893@localhost
LogLevel debug
Syslog true
RejectFailures false
ReportFailures true
HistoryFile /var/lib/opendmarc/opendmarc.dat
StatsSocket /var/run/opendmarc/opendmarc.sock
MinServers 3
ServerInterval 60
This logs activity to syslog and enables daily report emails.
Add your domain as the From address:
/etc/opendmarc/ignore.hosts
mail.example.com
Now enable OpenDMARC:
$ sudo systemctl enable opendmarc
$ sudo systemctl start opendmarc
Finally, generate the DMARC TXT record for your domain:
$ sudo opendmarc-gen-policy --domain example.com --policy none --report email:<a href="/cdn-cgi/l/email-protection" data-cfemail="3e4e514d4a535f4d4a5b4c7e5b465f534e525b105d5153">[email protected]</a>
Take this TXT record and add it to your domain’s DNS configuration.
OpenDMARC is now active and will validate incoming emails.
Testing the Mail Server
Our Ubuntu mail server should now be properly configured. Let’s do some testing to validate that it works.
First, send a test email from the server itself with:
$ echo "This is a test" | mail -s Testing <a href="/cdn-cgi/l/email-protection" data-cfemail="e1949284938f808c84a18499808c918d84cf828e8c">[email protected]</a>
Check if the mail was delivered:
$ sudo ls -l /var/mail
You should see a file named after the user you sent it to if delivery was successful.
Next, configure an email client like Thunderbird to connect to the mail server. Add a new account using the IMAP and SMTP credentials you configured.
Send a test message to the email address on your domain. It should be delivered to the user’s inbox folder on the Ubuntu server.
You can also use Telnet to manually connect to Postfix SMTP and send a message:
$ telnet mail.example.com 25
Type EHLO
, then MAIL FROM:
, RCPT TO:
and finally the test message data. This validates that SMTP sending and delivery are working properly.
Check /var/log/mail.log and /var/log/syslog for any errors with Postfix, Dovecot, MySQL or OpenDMARC during testing. Debug and resolve any issues that come up.
When everything is working as expected, your Ubuntu mail server is ready for use!
Securing the Mail Server
Now that we have a functioning mail server, let’s talk about some best practices for securing it:
- Keep your server updated: Regularly apply security patches and updates to your Ubuntu server and all mail server components.
- Use strong passwords: Enforce strong password policies for all user accounts.
- Implement rate limiting: Limit the number of emails that can be sent from a single IP address to prevent spam.
- Use TLS encryption: Ensure that all email traffic is encrypted using TLS to protect against eavesdropping.
- Monitor your logs: Regularly monitor your mail server logs for any suspicious activity.
- Implement a firewall: Configure a firewall to restrict access to your mail server to only necessary ports.
- Regular backups: Implement a robust backup strategy for your mail server data.
Following security best practices will help protect your mail server and users’ private information. The key things are restricting access, staying up to date, monitoring activity, backing up data, and using encryption. How to setup a mail server on Ubuntu requires security considerations.
Conclusion
That concludes this step-by-step guide on deploying a mail server on Ubuntu 20.04. We installed and configured Postfix, Dovecot, MySQL, and OpenDMARC. We also covered important security measures to protect the mail server.
With your own Ubuntu mail server, you can fully control your email while improving privacy, security and deliverability. Users can access mail over IMAP and SMTP using any standard email client.
Running a mail server takes more hands-on maintenance compared to using a hosted email provider. But the benefits of having your own private server often outweigh the extra effort. This guide explained how to setup a mail server on Ubuntu.
Let me know if you have any other questions! I’m happy to provide more details on any part of the mail server setup process.
Alternative Solutions for Setting Up a Mail Server on Ubuntu
While the above guide details a robust, albeit complex, method for setting up a mail server on Ubuntu, alternative solutions exist that offer different trade-offs in terms of complexity, control, and resource utilization. Here are two alternative approaches:
1. Using a Pre-packaged Mail Server Solution (Mail-in-a-Box)
Explanation:
Mail-in-a-Box is an open-source project that aims to make setting up a mail server as simple as possible. It automates much of the configuration process, handling tasks like installing Postfix, Dovecot, and other necessary components. It also provides a user-friendly web interface for managing domains, users, and other settings. This simplifies how to setup a mail server on Ubuntu.
Advantages:
- Ease of Use: Significantly reduces the complexity of setting up a mail server.
- Comprehensive: Includes all essential components for a fully functional mail server.
- Web Interface: Provides a convenient way to manage the server.
- Automatic Configuration: Handles much of the configuration automatically, reducing the risk of errors.
Disadvantages:
- Less Control: You have less control over the individual components and their configurations compared to a manual setup.
- Security Considerations: Relies on the security measures implemented by Mail-in-a-Box, requiring you to trust the project’s security practices.
- Customization Limitations: Customization options may be limited compared to a manual setup.
Implementation:
-
Download and Run the Installer:
Follow the instructions on the Mail-in-a-Box website to download and run the installer script on your Ubuntu server. -
Answer Configuration Questions:
The installer will ask you a series of questions about your domain name, hostname, and other settings. -
Wait for the Installation to Complete:
The installer will automatically install and configure all necessary components. -
Access the Web Interface:
Once the installation is complete, you can access the web interface through a web browser to manage your mail server.
Code Example:
While Mail-in-a-Box automates the process, here’s a conceptual snippet of how it might set up a basic Postfix configuration (this is for illustrative purposes only; you wouldn’t manually enter this with Mail-in-a-Box):
# Conceptual Postfix configuration snippet (Mail-in-a-Box automation)
echo "myhostname = mail.example.com" >> /etc/postfix/main.cf
echo "mydomain = example.com" >> /etc/postfix/main.cf
echo "inet_interfaces = all" >> /etc/postfix/main.cf
systemctl restart postfix
2. Using Docker and Pre-built Mail Server Images (Docker-Mailserver)
Explanation:
Docker-Mailserver is a project that provides a collection of Docker images for setting up a mail server. Docker allows you to containerize applications, making them easier to deploy and manage. With Docker-Mailserver, you can quickly deploy a mail server with all the necessary components (Postfix, Dovecot, etc.) pre-configured within Docker containers.
Advantages:
- Simplified Deployment: Docker simplifies the deployment process, making it easy to get a mail server up and running quickly.
- Isolation: Docker containers provide isolation between the mail server components and the host system, improving security and stability.
- Scalability: Docker makes it easier to scale the mail server by adding more containers as needed.
- Reproducibility: Docker ensures that the mail server environment is consistent across different systems.
Disadvantages:
- Docker Knowledge Required: Requires some familiarity with Docker concepts and commands.
- Resource Overhead: Docker containers can consume more resources than a native installation.
- Configuration Complexity: While Docker simplifies deployment, configuring the mail server within the containers may still require some technical knowledge.
Implementation:
-
Install Docker: Install Docker on your Ubuntu server.
-
Clone the Docker-Mailserver Repository: Clone the Docker-Mailserver repository from GitHub.
-
Configure the Environment Variables: Configure the environment variables in the
docker-compose.yml
file to set up your domain name, hostname, and other settings. -
Start the Docker Containers: Run the
docker-compose up -d
command to start the Docker containers. -
Access the Web Interface (if applicable): Some Docker-Mailserver setups include a web interface for managing the server.
Code Example:
Here’s a snippet from a docker-compose.yml
file used with Docker-Mailserver:
version: "3.9"
services:
mailserver:
image: ghcr.io/docker-mailserver/docker-mailserver:latest
container_name: mailserver
hostname: mail.example.com
ports:
- "25:25"
- "143:143"
- "587:587"
- "993:993"
volumes:
- ./data/dms:/var/mail
- ./data/config:/tmp/docker-mailserver/dms-data/config
environment:
- ENABLE_SPAMASSASSIN=1
- ENABLE_CLAMAV=1
- ONE_DIR=1
- DMS_UID=1000
- DMS_GID=1000
- POSTMASTER_ADDRESS=<a href="/cdn-cgi/l/email-protection" data-cfemail="572224322539363a3217322f363a273b327934383a">[email protected]</a>
- PERMIT_DOCKER=network
restart: always
These alternatives offer different approaches to how to setup a mail server on Ubuntu, each with its own set of advantages and disadvantages. The best choice depends on your specific needs and technical expertise.