Sign In
Sign In

How to Set Up Your Own Email Server

How to Set Up Your Own Email Server
Hostman Team
Technical writer
Mail
17.10.2024
Reading time: 12 min

A mail server is a system that manages the correct delivery of emails from the sender to the recipient. For instance, when you send an email via Gmail, you’re using Google’s mail server.

A mail client, on the other hand, is a program used to read, send, and store emails. Examples of mail clients include Microsoft Outlook, Thunderbird, and others.

Protocols for Receiving and Sending Emails

SMTP (Simple Mail Transfer Protocol)

The outgoing mail server uses the SMTP protocol, which stands for "Simple Mail Transfer Protocol." Its primary job is to relay messages between the sender and recipient. SMTP has two main functions:

  1. Verifying the sender's configuration and allowing the sending device to transmit the email.

  2. Sending the message and receiving the response code.

SMTP servers use ports 25 (unencrypted) and 465 (encrypted) for sending emails.

POP3 (Post Office Protocol)

POP3 is a protocol for receiving emails. It allows a mail client to connect to the server and download the email to the local device, making it available for offline access. However, the email is typically removed from the remote server after downloading (though there's an option to keep a copy on the server).

POP3 operates on ports 110 (unencrypted) and 995 (SSL/TLS encrypted).

IMAP (Internet Message Access Protocol)

Like POP3, IMAP is used to receive emails, but it allows you to manage the messages directly on the server without downloading them locally. This is useful for accessing your email from multiple devices.

IMAP uses ports 143 (unencrypted) and 993 (SSL/TLS encrypted).

Why Set Up Your Own Email Server?

The most common answer is: “To use your own domain in your email address.” While this is true, it's not the full picture.

You can use your custom domain without setting up a dedicated mail server. Many services allow you to connect your domain to their mail servers. All you need to do is buy a domain and link it to their servers in the settings. The main advantage of this approach is that they already have a configured SMTP server. This means you don't need to deal with complicated tasks like configuring forwarding, setting up anti-spam filters, or managing other advanced settings. You simply need to correctly set the NS records (Name Server records), which is much easier than setting up your own mail server.

However, using third-party services comes with limitations:

  1. Limited control: You won’t have full control over how your email operates.

  2. Sending limits: Every company has its own limits on how many emails you can send. If you send a large volume of emails (e.g., for corporate use or newsletters), these limits might be restrictive.

If you decide to create your own mail server, you’ll need to manage:

  • Email quotas and sending limits.

  • Backups to avoid losing data.

  • Avoiding spam blacklists.

  • Setting up access permissions if multiple people are using the same mail system.

Creating and maintaining your own email server gives you more control but also requires a higher level of technical expertise and responsibility.

Setting Up an Email Server

In this guide, we'll explore how to create your own email server. For this purpose, we'll use a Hostman cloud server, selecting Ubuntu 20.04 as the operating system.

The mail server we configure will support encryption, have anti-spam protection, and include a web-based admin panel for managing emails.

Preparing the Server

The first step is to switch to the superuser root mode:

sudo su

Before installing the necessary software, update the server packages:

apt update && apt upgrade

Next, check whether the server's hostname matches the domain of your email:

hostname

If the response shows something different from your desired server name, use the following command:

hostnamectl set-hostname mail.hostname.com

Here, replace mail.hostname.com with your actual hostname.

For the mail server and schedulers to work correctly, we need to configure the time zone by installing the time synchronization package chrony:

apt install chrony
timedatectl set-timezone Europe/Athens

You can choose the appropriate timezone using the command:

timedatectl list-timezones

Start the chrony service:

systemctl enable chrony

Next, we need to open the necessary ports for the mail server using the iptables utility. The required ports are:

  • 25, 465 — SMTP (for sending mail)

  • 110, 995 — POP3 (for receiving mail)

  • 143, 993 — IMAP (for receiving mail)

  • 80, 443 — HTTP (for web services)

The first port in each pair is for standard connections, and the second is for secure connections. Use iptables to open these ports:

iptables -I INPUT 1 -p tcp --match multiport --dports 25,110,143,465,587,993,995,80,443 -j ACCEPT

Since iptables rules are only stored for the current session and will reset after a reboot, we need to make them persistent:

netfilter-persistent save

Now, with the server properly set up, we can proceed to install the necessary software to create a fully functional mail server.

Installing and Configuring Postfix

Postfix is an open-source mail transfer agent (MTA). It has a modular architecture, which means it doesn't require running as the root user. Let's install Postfix and the postfix-mysql package for database integration:

apt install postfix postfix-mysql

During installation, select Internet Site when prompted. This assumes you have access to edit DNS records and can specify an FQDN (Fully Qualified Domain Name). In the next window, keep the server name as is and continue.

After installation, create a new user account to handle mail operations. First, create a group called vmail using groupadd:

addgroup -gid 1080 vmail

Next, create the vmail user and assign the home directory to /home/mail:

adduser --home /home/mail -gid 1080 -uid 1080 vmail

Where 1080 is the group ID (GID) and user ID (UID). If 1080 is already taken, you can choose a different value. Verify that the /home/mail directory belongs to the vmail user and group:

ll /home

Configuring Postfix

With the user created, proceed to configure Postfix by editing the main configuration file /etc/postfix/main.cf:

nano /etc/postfix/main.cf

Make the following edits:

# Domains we accept mail for
mydestination = localhost.$mydomain, localhost, localhost.localdomain
# Postfix protocol
inet_protocols = ipv4
# Path to the public certificate
smtpd_tls_cert_file = /etc/ssl/mail/public.pem
# Path to the private certificate
smtpd_tls_key_file = /etc/ssl/mail/private.key
Then, add additional options required for Postfix to function correctly:
# Mail storage location
virtual_mailbox_base = /home/mail
# Path to alias maps
virtual_alias_maps = proxy:mysql:/etc/postfix/mysql_virtual_alias_maps.cf
# Domain storage format
virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql_virtual_domains_maps.cf
# Mailbox storage format
virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
# Minimum virtual user ID
virtual_minimum_uid = 1080
# UID for the main user handling mail
virtual_uid_maps = static:1080
# GID for the group handling mail
virtual_gid_maps = static:1080
# Register Dovecot as the mail delivery agent
virtual_transport = dovecot
# Enable secure authentication
smtpd_sasl_auth_enable = yes
smtpd_sasl_exceptions_networks = $mynetworks
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
# Enable TLS encryption for outgoing SMTP connections
smtp_use_tls = yes
# Enable TLS support for incoming connections
smtpd_use_tls = yes
smtpd_tls_auth_only = yes
smtpd_helo_required = yes

Now, create the files referenced in the Postfix configuration. Start with the alias maps:

nano /etc/postfix/mysql_virtual_alias_maps.cf

Add the following content:

user = postfix
password = postfixPa$$w0rd
hosts = localhost
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = '1'

Similarly, configure the domain maps:

nano /etc/postfix/mysql_virtual_domains_maps.cf

Add:

user = postfix
password = postfixPa$$w0rd
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%u'

Finally, configure the mailbox maps:

nano /etc/postfix/mysql_virtual_mailbox_maps.cf

Add:

user = postfix
password = postfixPa$$w0rd
hosts = localhost
dbname = postfix
query = SELECT CONCAT(domain,'/',maildir) FROM mailbox WHERE username='%s' AND active = '1'

Edit the master.cf file:

nano /etc/postfix/master.cf

Add the following settings:

submission   inet  n  -  n  -  -  smtpd
-o smtpd_tls_security_level=may
-o smtpd_sasl_auth_enable=yes
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=/var/spool/postfix/private/auth
-o smtpd_sasl_security_options=noanonymous
-o smtpd_sasl_local_domain=$myhostname
smtps   inet  n  -  n  -  -  smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
dovecot   unix  -  n  n  -  -  pipe
flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -d ${recipient}

Generating Security Certificates

To ensure secure email transactions, generate security certificates using openssl. First, create the directory where the certificates will be stored (as specified in the main.cf file):

mkdir -p /etc/ssl/mail

Generate the certificates:

openssl req -new -x509 -days 1000 -nodes -out /etc/ssl/mail/public.pem -keyout /etc/ssl/mail/private.key -subj "/C=CY/ST=Limassol/L=Limassol/O=Global Security/OU=IT Department/CN=mail.devnullhost.com"

Finally, enable and restart Postfix:

systemctl enable postfix && systemctl restart postfix

Installing and Configuring Dovecot

Dovecot is an open-source IMAP and POP3 server. We'll install it along with the required modules for database integration:

apt install dovecot-imapd dovecot-pop3d dovecot-mysql

Next, we configure the mail storage method. Open the Dovecot configuration file:

nano /etc/dovecot/conf.d/10-mail.conf

In the file, specify the directory structure for storing mail. We'll use a hierarchy of domain → user:

mail_location = maildir:/home/mail/%d/%u/

In the same file, configure the authentication method:

service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0666
user = postfix
group = postfix
}
unix_listener auth-userdb {
mode = 0600
user = vmail
group = vmail
}
}
service stats {
unix_listener stats-reader {
user = vmail
group = vmail
mode = 0660
}
unix_listener stats-writer {
user = vmail
group = vmail
mode = 0660
}
}

Edit the Dovecot authentication configuration file:

nano /etc/dovecot/conf.d/10-auth.conf

Replace the line !include auth-system.conf.ext with !include auth-sql.conf.ext, indicating that SQL-based authentication should be used.

Next, configure SSL encryption in Dovecot:

nano /etc/dovecot/conf.d/10-ssl.conf

In this file, add the following:

ssl = required
ssl_cert = </etc/ssl/mail/public.pem
ssl_key = </etc/ssl/mail/private.key

When users connect for the first time, we want their mailboxes to be automatically created. To enable this, open the following file:

nano /etc/dovecot/conf.d/15-lda.conf

Add the following line:

lda_mailbox_autocreate = yes

Now, configure Dovecot to connect to the database. Open the SQL configuration file:

nano /etc/dovecot/dovecot-sql.conf.ext

Add the following lines to configure MySQL:

driver = mysql
connect = host=localhost dbname=postfix user=postfix password=postfixPa$$w0rd
default_pass_scheme = MD5-CRYPT
password_query = SELECT password FROM mailbox WHERE username = '%u'
user_query = SELECT maildir, 1080 AS uid, 1080 AS gid FROM mailbox WHERE username = '%u'
user_query = SELECT CONCAT('/home/mail/',LCASE(`domain`),'/',LCASE(`maildir`)), 1080 AS uid, 1080 AS gid FROM mailbox WHERE username = '%u'

Open the main Dovecot configuration file to set up the server interface:

nano /etc/dovecot/dovecot.conf

In this file, add the following line to listen on all available network interfaces:

listen = *

Finally, enable and restart Dovecot to apply the configuration:

systemctl enable dovecot && systemctl restart dovecot

Installing and Configuring PostfixAdmin

For PostfixAdmin to work correctly, you need a configured web server, PHP, and a MySQL database (either a LAMP or LEMP stack). In this guide, we will skip the web server setup and go directly to installing PostfixAdmin.

First, install the necessary PHP extensions:

apt install php-mysql php-mbstring php-imap

Download PostfixAdmin to the web server's root directory using wget:

wget https://sourceforge.net/projects/postfixadmin/files/latest/download -O postfixadmin.tar.gz

Create a directory for PostfixAdmin and extract the archive contents:

mkdir -p /var/www/html/postfixadmin && tar -C /var/www/html/postfixadmin -xvf postfixadmin.tar.gz --strip-components 1

Then, create a directory for storing template caches:

mkdir /var/www/html/postfixadmin/templates_c

Set the correct permissions for the web server to access the PostfixAdmin directory:

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

Create the database and a user for PostfixAdmin:

mysql -u root
CREATE DATABASE postfix DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
GRANT ALL ON postfix.* TO 'postfix'@'localhost' IDENTIFIED BY 'postfixPa$$w0rd';
exit;

In the local configuration file of PostfixAdmin, add the database configuration:

nano /var/www/html/postfixadmin/config.local.php

The file contents should be:

<?php
$CONF['configured'] = true;
$CONF['default_language'] = 'en';
$CONF['database_password'] = 'postfixPa$$w0rd';
$CONF['emailcheck_resolve_domain']='NO';
?>

Open the PostfixAdmin setup page in your browser by going to /postfixadmin/public/setup.php. You will be prompted to generate a password hash for authentication.

Enter the password and click the button. A message containing the hash will appear below the form. Copy this hash and insert it into the config.local.php file:

nano /var/www/html/postfixadmin/config.local.php

Refresh the /postfixadmin/public/setup.php page and log in with the password you used to generate the hash. If everything is configured correctly, you should see a configuration check page.

At the bottom of this page, there is a form to create an admin account. After successfully creating the admin, go to /postfixadmin/public/login.php and log in with the credentials you just set up.

You will be redirected to the PostfixAdmin administration panel.

Creating a Mailbox in PostfixAdmin

In your browser, go to /postfixadmin/public/. In the top menu, choose "Domain List → New Domain."

Then, in the "Overview → Create Mailbox" section, enter the details for a test email account.

You can now test the connection using email clients. Use the following connection parameters:

  • Server: Your server's hostname

  • IMAP: Port 143, STARTTLS

  • POP3: Port 110, STARTTLS

  • SMTP: Port 25, STARTTLS

  • Login and Password: The credentials you specified when creating the mailbox

Conclusion

In this guide, we explored what a self-hosted email server is and the technologies and software used to configure it.

The main advantage of having your own mail server is the ability to fully customize it: create unlimited mailboxes, assign aliases, and manage users. All these features can be implemented by renting a cloud server from Hostman and configuring the server following this guide.

Mail
17.10.2024
Reading time: 12 min

Similar

Mail

How to Use Google SMTP Server

SMTP stands for "Simple Mail Transfer Protocol." As the name suggests, it is a protocol for sending and delivering emails to the recipient. If you decide to set up your own mail server, you can use Hostman's cloud servers.  What is an SMTP server? An SMTP server is a server responsible for ensuring the proper functioning of the SMTP protocol. Its main role is to act as a relay between the sender and the recipient. The SMTP server performs two essential tasks: Verifies the configuration of the device attempting to send a message and permits it to do so. Sends the message to the specified address and receives a response code. An SMTP server's responsibility ends here — it only handles sending emails. Receiving emails on the recipient's side is managed by other protocols, such as POP3 and IMAP. Basic steps of sending an email: The sender's server gathers the necessary information — such as the sender's and recipient's addresses, along with the message itself containing the required fields. The sender's server identifies the recipient's email provider by analyzing the recipient's email address and requests the IP address of the recipient's mail server. The sender's server receives a response from the recipient's server. If there is no response from the recipient's server, the sender's server will attempt to establish a connection multiple times. If there is still no response, an error code is returned. The standard port for SMTP is 25, but other ports like 465 and 587 are also used for secure SSL connections and mandatory authentication. It's worth noting that some providers block port 25 to prevent spam, so it's a good idea to check this with your provider. For SMTP, you can use cloud servers in almost any configuration. However, if you plan to send large volumes of emails or need to ensure that your emails are not marked as spam, using Google's SMTP server is recommended. Advantages of Using Google's SMTP Server Cost: One of the most obvious advantages is that Google SMTP is entirely free — you only need a Google account to use it. Pre-configured: Setting up and managing a mail server is quite complex and requires theoretical knowledge of network protocols and practical experience with server configuration. Using an external solution like Google's saves a lot of time configuring the server. Backup: You don't need to worry about the server's uptime — if something goes wrong in the middle of the night, Google's team will handle it. Google also takes care of backing up both sent and received emails, saving you the trouble of ensuring the security of valuable or confidential information. Indexing: Another advantage of storing emails on Google's servers is that indexing and searching through emails are powered by Google's computational resources. If you use the same SMTP for Gmail, emails will automatically appear in the "Sent" and "Inbox" folders, keeping everything organized in one place. Spam Protection: One of the biggest challenges with managing your own mail server is preventing emails from being marked as spam. When sending through Google's SMTP server, you can be confident that the email will arrive at the recipient's inbox just like any other Gmail message. Since Google doesn't use the standard port 25 for sending emails, the likelihood of the message being marked as spam or blocked by the recipient's provider is reduced. Disadvantages of Using a Third-Party SMTP Server Data storage on a remote server: One common concern with third-party SMTP servers is that all your communication is stored under Google's control. However, privacy concerns about keeping emails on your own servers are still valid, especially if you are communicating with average users who are unlikely to use their own SMTP servers. Email limits: Google limits the number of emails sent per day to 100. This limit is generally sufficient if you're testing the SMTP sending mechanism or your project doesn't require large volumes of outgoing emails. Setting Up Google SMTP You'll need access to a Google account to set up the Google SMTP service. In most cases, a simple login and password are sufficient. Still, if you have enabled two-factor authentication (which is highly recommended), you must generate an app-specific password. Here are the settings you'll need to configure Google's SMTP server: SMTP Server (Outgoing Mail Server): smtp.google.com SMTP Username: Your full email address SMTP Password: Your Google account password or the app password you generated SMTP Port: 465 Requires TLS/SSL?: Yes Note that Google will automatically overwrite the From header of any email you send via the SMTP server if it doesn't match your default email address. For instance, if you try to send an email from a non-existent address, Google will replace it with your real one. This is standard behavior, but you can adjust this in your email settings. Email Clients Besides sending automated emails using Google's SMTP server, you can also use these settings to connect with email clients like Thunderbird or Outlook. This way, you can send emails without using a browser or Google's standard client. However, to receive emails from your Google account in another client, you'll need to use POP3 or IMAP protocols. These settings are available in the same place as other Gmail mail settings, under the "Forwarding and POP/IMAP" section. Testing Email Sending We'll write a simple PHP script to test the configuration provided above. We'll send the email using the PHPMailer package, which we can install via the Composer dependency manager: composer require phpmailer/phpmailer Next, create a file index.php where we will specify the SMTP server settings and attempt to send a test email. <?php error_reporting(E_ALL); // Show all errors // Include PHPMailer require dirname(__FILE__) . '/vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); // Specify that we are using SMTP $mail->isSMTP(); // Enable debugging output for testing purposes $mail->SMTPDebug = 2; $mail->Debugoutput = 'html'; // Provide the SMTP credentials $mail->Host = 'smtp.gmail.com'; // SMTP host $mail->Port = 587; // SMTP port $mail->SMTPSecure = 'tls'; // Encryption $mail->SMTPAuth = true; // Enable authentication $mail->Username = "user@gmail.com"; // Your Google account email $mail->Password = "62584jattjjtmxnpwf124"; // App-specific password // Specify sender and recipient information $mail->setFrom('test-mail@hostman.com', 'Test Sender Hostman); // Sender $mail->addReplyTo('replyto@example.com', 'First Last'); // Reply-To address $mail->addAddress('mail@yahoo.com', 'James Smith'); // Recipient // Subject and content $mail->Subject = 'Hostman: Google SMTP Test'; // Subject line $mail->msgHTML('<h1>Hello, Hostman</h1>'); // HTML content $mail->AltBody = 'This is a plain-text message body'; // Plain-text fallback // Output the result if (!$mail->send()) { echo "Mailer Error:". $mail->ErrorInfo; } else { echo "Message sent!"; } You can use the same script by replacing the credentials and recipients with your own information, including the Reply-To address. Now, execute the PHP script through the browser by loading the page. If everything is set up correctly, you'll see the output of the email being sent. If any credentials are incorrect, PHPMailer will display an error message. Next, open your email client and check if the email has arrived. Everything should work as expected, and you'll also see the email in the Sent folder in your Gmail account. Conclusion In this article, we explored the advantages of using Google's SMTP server, including the free setup and maintenance, reliable backup, and reduced likelihood of emails being marked as spam. Additionally, we wrote a simple PHP script to demonstrate how to send emails via Google SMTP. We also discussed some limitations and drawbacks of using third-party email services.
15 April 2025 · 7 min to read
Mail

Roundcube Webmail: The Complete Guide to Setup, Features, and Customization

Roundcube is a browser-based email client. It provides easy access to manage emails via a web interface. Roundcube can be installed in two ways: either by deploying it with Docker Compose or by directly installing it on an Ubuntu server for a more hands-on approach. Why Use Roundcube Webmail Here are some of the key features that make Roundcube stand out as an email client: User-Friendly Interface: Roundcube interface is easy to use, minimal, and modern. IMAP and SMTP Support: It supports both IMAP and SMTP protocols, ensuring compatibility with most email servers. Multiple Email Accounts: Users can configure multiple email accounts within the same interface and switch between them easily. Web-Based: All you need is a browser to access your emails. This makes it a convenient option for users who often need to switch devices. Extensible and Customizable: Roundcube is open source. With access to hundreds of its plugins, you can customize it to your liking. Address Book: Having an address book is crucial for email management.  With its address book integration, you can import existing contacts as well as create a new contact manually. Prerequisites To proceed with this tutorial, you’ll need: An Ubuntu Server: This tutorial uses the Ubuntu 22.04 server but for the most part, it should work on other modern versions as well. Docker and Docker Compose (for Method 1): If not installed, you can install them with the commands: sudo apt updatesudo apt install docker docker-compose Method 1: Setup Roundcube with Docker Compose (Recommended) Docker containers encapsulate all the necessary dependencies to ease the overall setup process. Here’s a working docker-compose.yml file to launch the Roundcube webmail with thunderbird_labels, show_folder_size, and tls_icon plugins. version: '3' services: roundcubemail: image: roundcube/roundcubemail:latest container_name: roundcubemail volumes: - ./www:/var/www/html - ./db/sqlite:/var/roundcube/db ports: - 9002:80 environment: ROUNDCUBEMAIL_DB_TYPE: sqlite ROUNDCUBEMAIL_SKIN: elastic ROUNDCUBEMAIL_DEFAULT_HOST: "ssl://imap.yandex.ru" ROUNDCUBEMAIL_SMTP_SERVER: "ssl://smtp.yandex.ru" ROUNDCUBEMAIL_DEFAULT_PORT: 993 ROUNDCUBEMAIL_SMTP_PORT: 465 ROUNDCUBEMAIL_COMPOSER_PLUGINS: "weird-birds/thunderbird_labels,jfcherng-roundcube/show-folder-size,germancoding/tls_icon:^1.2" ROUNDCUBEMAIL_PLUGINS: thunderbird_labels, show_folder_size, tls_icon Here’s an explanation of what each environment variable refers to: ROUNDCUBEMAIL_SKIN: It tells what theme to use for the interface. Elastic is the modern theme for Roundcube. Classic is an older, more basic theme. ROUNDCUBEMAIL_DEFAULT_HOST: The default IMAP hosts that Roundcube will look at and try to connect.  ROUNDCUBEMAIL_DEFAULT_PORT: IMAP port number. ROUNDCUBEMAIL_SMTP_SERVER: This SMTP server will be utilized to send emails.  ROUNDCUBE_SMTP_PORT: SMTP port number. ROUNDCUBEMAIL_COMPOSER_PLUGINS: These add-ons can enhance the email experience, customizing appearances and features to Roundcube. These plugins further need to be enabled with the ROUNDCUBEMAIL_PLUGINS variable. ROUNDCUBEMAIL_PLUGINS: ROUNDCUBEMAIL_COMPOSER_PLUGINS only installs the plugin while the ROUNDCUBEMAIL_PLUGINS variable activates those plugins. Your email provider will provide details regarding the IMAP server, IMAP port, SMTP server, and SMTP settings. So, based on your email provider, you need to adjust these variables. Also, you need to note what encryption your email provider offers. It might be SSL/TLS. To deploy this docker-compose file, ensure you have first set up docker and docker-compose. docker --version && docker-compose --version  Start the docker service: systemctl start docker Deploy the docker-compose.yml file: docker-compose up It might take 2-3 minutes to get Roundcube running on <your-server-ip>:9092. To start managing your emails, enter the login credentials provided by your email server.  If you’re using Gmail or Outlook, the username will be your email address along with @gmail or @outlook suffix. After a successful login, you’ll get to see a similar interface. Method 2: Direct Install on the Ubuntu Server Roundcube is a LAMP stack application. It’s written using PHP and supports multiple database backends, including MySQL, PostgreSQL, and SQLite.  Step 1: Install PHP and Apache Before installation, update the list of available packages and their versions. sudo apt updatesudo apt install php apache2 You need to install and enable some PHP extensions as well. sudo apt install php-mbstring php-xml php-imap php-sqlite3 php-json php-curl php-zip php-gd php-intl Here’s a list of what each extension does: php-mbstring: Provides support for multi-byte character encodings php-xml: Adds ability to work with XML documents php-imap: Allows to establish connections with IMAP server  php-sqlite3: PHP adapter to talk to SQLite database php-json: Handles JSON encoding and decoding php-curl: Allows sending HTTP requests via curl binary php-zip: Handles reading and writing of zip files php-gd: Provides image manipulation capabilities php-intl: Provides support for multiple languages, cultures, and regional preferences Step 2: Download the Roundcube Source code You can download the source code from https://roundcube.net/download/. To facilitate deployment, choose the Complete Stable Version. Download the application in the /var/www directory. cd /var/wwwsudo wget https://github.com/roundcube/roundcubemail/releases/download/1.6.10/roundcubemail-1.6.10-complete.tar.gz Step 3: Extract and Assign Permissions One simple way to allow Apache to read from and write to the document root is to change ownership to www-data user. sudo tar xvf roundcubemail-1.6.10-complete.tar.gzsudo chown -R www-data:www-data roundcube-1.6.10cd roundcube-1.6.10 Step 4: Setup the Configuration File  The config file determines what plugins will be in use, which interface and skins will be in use, what SMTP and IMAP server the email client will connect to, etc. Make a copy of the default config file (first, ensure your current directory is /var/www/roundcube-1.6.10): sudo cp config/config.inc.php.sample config/config.inc.php Open the config file and edit these important settings i.e. the database connection, IMAP server, and SMTP server. sudo nano config.inc.php Here’s a sample config for the Outlook email server. You need to adjust db_dsnw, imap_host, and smtp_host as per your email provider. This configuration uses an SQLite database for simplicity. $config[‘db_dsnw’] = ‘sqlite:////var/www/roundcubemail-1.6.10/config/db.sqlite?mode=0640’;$config[‘imap_host’] = ‘ssl://imap.office365.com:993’;$config[‘smtp_host’] = ‘ssl://smtp-mail.outlook.com:587’; If you want to use some plugins, you need to download them manually in the plugins directory or use Composer to manage plugins. Then enable the config file as: Step 5: Configure Apache  Create a new file roundcube_site.conf under /etc/apache2/sites-available with the contents: <VirtualHost *:80> DocumentRoot /var/www/roundcubemail-1.6.10 # ServerName roundcube.CHANGEME_YOURDOMAIN.com # Replace it ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/roundcubemail-1.6.10> AllowOverride All Require all granted </Directory> # Block access to the database <FilesMatch "\.sqlite$"> Require all denied </FilesMatch> </VirtualHost> Enable the newly created Apache site: sudo a2ensite roundcube_site.conf Disable the default Apache site as it might cause the issue: sudo a2dissite 000_default.conf Restart Apache to load changes: sudo systemctl reload apache2 Step 6: Launch and Install Finally, you can launch the Roundcube interface simply by visiting the IP of your server. It’ll ask for Username and Password. You can get those credentials from your email provider. Troubleshooting A quick tip, in case the setup is not working, inspect the errors.log file. Also, inspecting the Apache access.log and error.log files can provide additional clues. tail -f /var/log/apache2/access.logtail -f /var/log/apache2/error.log Multi-account management To add additional email accounts, switch to the Settings tab, select Identities, and then click on the Create icon. Import Contacts You can import all your previous contacts from a vCard or CSV file. To do so, head over to the Contacts tab and click on Import icon on top. If you want to import CardDAV, add composer plugins roundcube/carddav.  Collected Recipients will bring a list of contacts that had been previously contacted. Similarly, Trusted Senders will bring a list of a sender. Useful Roundcube Plugins It’s worthwhile to mention some of the popular plugins : Larry: The Larry theme. Contextmenu: It enables right-click context menus on various parts of interfaces. Gravatar: Fetches gravatar images for the email. Identity_switch: Lets you switch to different user identities from a single session. Advanced Search: Search through emails in a quick and fast way. Sauserprefs: It fights spam in your mailbox. Calendar: Provides calendar integration. Roundcube_caldav: CalDAV allows managing events on central calendar systems like Google Calendar.  It’s a must-have plugin for efficient team collaboration. Identity SMTP : It lets you set SMTP configurations for different identities. Carddav: This plugin provides a standard way to store and import contact information in a vCard format. Customizr: This lets you customize logos and styles. Fail2ban: Shows the number of failed attempts.  Html5_notifier: It sends you desktop notifications for any email activity. Thunderbird_labels: Assigns a tag to emails. Roundcube Alternatives If you didn’t like the Roundcube experience, there are other alternatives to consider. Horde Webmail: Horde offers an integrated suite of applications such as email, calendar, and task management together. It provides enhanced productivity for team collaboration. Zimbra Webmail: Zimbra is available in two different versions i.e. open source and commercial. It’s known for enterprise-grade security, spam filtering, and two-factor authentication. Rainloop: It features a sleek and modern design. It requires no database to set up. Rainloop is known for its simplicity. Roundcube Webmail: Is It the Right Fit for You? Roundcube offers hundreds of plugins to customize the experience. With its docker deployment, the Roundcube mail client can be deployed within a matter of a few minutes. If you’re comfortable with server management and need a lightweight, open-source webmail solution, Roundcube could be a perfect fit for you. However, if you require more advanced features or don’t want the hassle of self-hosting, you might want to consider other options.
25 March 2025 · 9 min to read
Mail

How to Send Email in Linux from the Command Line with Sendmail and Mailx

For those managing servers or working on automation tasks, knowing how to send emails from the Linux terminal is essential. It offers complete control over email functions and eliminates the need for complex mail programs. This is useful in scenarios where speed and simplicity matter most. Common tools such as sendmail and mailx are frequently used for sending messages, checking SMTP settings, automating alerts, and integrating with scripts. They are straightforward yet effective, making them perfect for tasks like informing teams about server updates, automating reports, or testing email setups. This guide is designed for users looking to manage their email directly from the terminal. It covers the installation of essential tools and delves into more advanced tasks, such as sending attachments and configuring email tools. Why Choose Command-Line Email Tools? Two commonly used tools, sendmail and mailx, are reliable options for mail transmission in Linux. They come with a certain set of benefits: Efficiency: Traditional email software can be slow and resource-intensive. These tools enable quick and lightweight email sending directly from the terminal. Automation: They integrate smoothly with shell scripts, cron processes, and system monitoring tools. Automating mail alerts and notifications for repeated actions is possible via these Linux mail tools. Troubleshooting SMTP Problems: Debugging SMTP setups becomes more manageable. These commands provide visibility into message delivery, ensuring mail logs and errors are easier to inspect. Flexibility: Whether it’s sending alerts or generating automated reports, command-line tools like sendmail and mailx offer versatility across a range of tasks. Prerequisites  Before utilizing these Linux mail command line tools, ensure you have terminal access. Root privileges may be required in some cases, especially for configuring each mail command on Linux discussed in this guide. Setting Up a SMTP Server SMTP servers are essential for sending emails. These servers fall into two categories: External and Local SMTP servers. External SMTP Servers It refers to a mail server hosted by a third-party provider. These servers are utilized to deliver emails over the internet to recipients who are not part of your local network. They are built to manage global mail delivery while ensuring proper authentication, encryption, and spam prevention. Examples  Gmail  Address: smtp.gmail.com Port: 587 (with TLS) or 465 (with SSL) Outlook  Address: smtp.office365.com Port: 587 These servers need appropriate authentication methods (such as a username, password, or app-specific passwords) and encryption (like TLS or SSL) to ensure secure communication. Note: We’ve already provided a guide for setting up external SMTP servers. The command to send emails through Postfix remains the same as mentioned in this article. Simply configure the SMTP settings using our guide, and replace the email address with Gmail or any other preferred provider for proper email delivery. Local SMTP Servers This server functions solely within a private network or system. It is perfect for: Sending emails between users on the same network or domain (e.g., tom@office.local to jerry@office.local). Local testing and development tasks. Internal communication within an organization. Does not need internet access to operate, as they manage mail delivery internally. Setting Up a Local SMTP Server Here are the procedures to set up a local SMTP server using Postfix: Install Postfix via: sudo apt install postfix Modify the Postfix configuration file: sudo nano /etc/postfix/main.cf Update or confirm these key settings: myhostname = mail.office.local mydomain = office.local myorigin = $mydomain inet_interfaces = loopback-only local_recipient_maps = proxy:unix:passwd.byname mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain Save and exit the file after doing changes, then restart Postfix: sudo systemctl restart postfix To create email addresses like linux@office.local and hostman@office.local, set up user accounts on the server: sudo adduser linuxsudo adduser hostman Overview of sendmail sendmail is a prominent mail transfer agent (MTA) in Linux. It works flawlessly with SMTP servers for mail delivery and allows emails to be sent and routed from local systems or scripts.  Installing sendmail  Before sending emails, you must install the Linux sendmail tool. Execute the commands below based on your distribution: For Debian/Ubuntu sudo apt install sendmail For CentOS/Red Hat sudo yum install sendmail Starting and Enabling Service Once installed, make sure sendmail is running and configured to start at boot: sudo systemctl start sendmailsudo systemctl enable sendmail Testing the Configuration Check the sendmail is set up correctly by executing: echo "Testing sendmail setup" | sendmail -v your-email@example.com Verify email by executing the mail command: mail Note: Install mailutils package in case the mail command is not working. sudo apt install mailutils Or utilize the cat command: cat /var/mail/user Editing the Configuration File To customize settings for sendmail, modify the configuration file located at /etc/mail/sendmail.mc: sudo nano /etc/mail/sendmail.mc Make the required changes to fit your server. For example, if you want to define the domain name for your server, you can add or modify the following line: define(`confDOMAIN_NAME', `your_domain.com')dnl Here, replace your_domain with your actual domain name. Then rebuild the configuration file: sudo m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf If a "permission denied" error occurs, use: sudo sh -c "m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf" Finally, restart the service: sudo systemctl restart sendmail Sending Email Via sendmail With sendmail, you can easily deliver emails, customize subjects, and even add attachments using external tools. Let’s go over the process to send emails: Basic Example To send an email with sendmail, use the below-given instructions: First, create a file to hold the message: nano email.txt Add any content to the file, for example: Subject: Test Email from HostmanThis is a test email sent using sendmail on Linux. Deliver the file's contents: sendmail recipient@example.com < email.txt The contents of email.txt will be sent to the designated recipient. For verification, apply: mail Adding Attachments  sendmail by itself doesn’t support attachments. You’ll need to utilize uuencode or similar tools to include files. First, install sharutils for uuencode: sudo apt install sharutils Here’s how to attach a file: ( echo "Subject: Email with attachment"; uuencode file.txt file.txt ) | sendmail recipient@example.com In the above sendmail example we send an email with file.txt attached. To verify, apply the Linux command mail: mail Overview of mailx  The mailx Linux command is a simple and effective terminal application for managing emails. It is included in the mailutils package found in most Linux distributions. Installing mailx  Install mailutils package on your system to utilize the mailx command on Linux: For Debian/Ubuntu systems sudo apt install mailutils For Red Hat-based systems sudo yum install mailx Sending Email with mailx This is a simple example demonstrating the use of mailx. Include a subject line and message in your email: echo "This is the body of the email" | mailx -s "Test Email from Mailx" recipient@example.com Utilize the Linux mail command for verification: Example with Attachments Use the -A flag with the mailx command to send emails from Linux with attachments: echo "Please find the attached document" | mailx -s "Email with Attachment" -A email.txt recipient@example.com This sends email.txt as an attachment to the recipient. Conclusion Sending email from the Linux command line is an effective method for automating communication tasks, troubleshooting servers, or testing configurations. Using tools such as sendmail and mailx, you can manage everything from simple messages to more complex setups with attachments. This guide has provided detailed instructions to help you begin without difficulty. Utilize these Linux email commands to improve your workflow. If you face any issues, feel free to refer back to this tutorial.
18 March 2025 · 7 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support