Build Your Own Email Server on Ubuntu: Basic Postfix Setup

Why run your own email server? Perhaps you have a website, which needs to send emails to users, or maybe you want to store your emails on your own server to protect your privacy. However, building your own email server can be a pain in the butt because there are so many software components you need to install and configure properly. To make this journey easy for you, I’m creating a tutorial series on how to build your own email server on Ubuntu.

Build Your Own Email Server on Ubuntu Basic Postfix Setup

I’m confident to say that this is the best and most comprehensive tutorial series about building an email server from scratch on the Internet. Not only will you have a working email server, but also you will have a much better understanding of how email works. This tutorial series is divided into 15 parts.

  1. Setting up a basic Postfix SMTP server
  2. Set up Dovecot IMAP server and TLS encryption
  3. Create Virtual Mailboxes with PostfixAdmin (MariaDB/MySQL, PostgreSQL)
  4. Creating SPF and DKIM record to get through spam filters
  5. Setting Up DMARC to protect your domain reputation
  6. 7 Effective Tips to Stop Your Email From Being Marked as Spam
  7. Install Roundcube Webmail on Ubuntu (MySQL/MariaDB, PostgreSQL)
  8. How to Host Multiple Mail Domains in PostfixAdmin
  9. Blocking Email Spam with Postfix
  10. Blocking Email Spam with SpamAssassin
  11. Setting Up Amavis and ClamAV on Ubuntu Mail Server
  12. How to Secure Email Server Against Hacking with Self-hosted VPN Server
  13. How to Bypass Email Blacklists
  14. (optional) Enable and Configure Postscreen in Postfix to Block Spambots
  15. Automatic IP and Domain Warm-up For Your Email Server

I know this seems to be a very daunting task. However, based on what you want to achieve, you might not need to follow all of them. My articles are easy to follow, so if you dedicate some time to it, you will have a working email server.

Hint: If you don’t want to build an email server from scratch, which is a long and tedious process, you can use Scalahosting managed VPS to set up a full-featured mail server quickly and easily.

This article is part 1 of this tutorial series. In this article, I will show you how to set up a very basic Postfix SMTP server, also known as an MTA (message transport agent). Once you finish this article, you should be able to send and receive emails with your own email domain on your own email server. This tutorial is tested on Ubuntu 22.04, Ubuntu 20.04, and Ubuntu 18.04 server.

About Postfix

Postfix is a state-of-the-art message transport agent (MTA), aka SMTP server, which serves two purposes.

  • It’s responsible for transporting email messages from a mail client/mail user agent (MUA) to a remote SMTP server.
  • It’s also used to accept emails from other SMTP servers.

Postfix was built by Wietse Venema who is a Unix and security expert. It’s easy to use, designed with security and modularity in mind, with each module running at the lowest possible privilege level required to get the job done. Postfix integrates tightly with Unix/Linux and does not provide functionalities that Unix/Linux already provides. It’s reliable in both simple and stressful conditions.

Postfix was originally designed as a replacement for Sendmail – the traditional SMTP server on Unix. In comparison, Postfix is more secure and easier to configure. It is compatible with Sendmail, so if you uninstall Sendmail and replace it with Postfix, your existing scripts and programs will continue to work seamlessly.

In this tutorial, you will learn how to configure Postfix for a single domain.

Choosing the Right Hosting Provider

It’s not an easy task to find a VPS (Virtual Private Server) provider suitable for email hosting. Many hosting companies 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.

Another problem is that big well-known hosting providers like DigitalOcean or Vultr are abused by spammers. Often the server IP address is on several blacklists. Vultr has some entire IP ranges blacklisted.

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

  • They don’t block port 25.
  • 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 blacklists.
  • 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 limit, whatsoever. Note that you are not allowed to send spam, also known as unsolicited bulk email. If the recipient doesn’t explicitly give you permission to send emails, and you send emails to them, that’s unsolicited email.
  • 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.

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

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

Things To Do Before Installing Postfix

To make Postfix perform better and get the most out of Postfix, you need to properly set up your Ubuntu server.

Set A Correct Hostname for Ubuntu Server

By default, Postfix uses your server’s hostname to identify itself when communicating with other MTAs. Hostname can have two forms: a single word and FQDN.

The single word form is used mostly on personal computers. Your Linux home computer might be named linux, debian, ubuntu etc. FQDN (Fully Qualified Domain Name) is commonly used on Internet-facing servers and we should use FQDN on our mail servers. It consists of two parts: a node name and a domain name. For example:

is an FQDN. mail is the nodename, is the domain name. FQDN will appear in the smtpd banner. Some MTAs reject messages if your Postfix does not provide FQDN in smtpd banner. Some MTAs even query DNS to see if FQDN in the smtpd banner resolves to the IP of your mail server.

Enter the following command to see the FQDN form of your hostname.

hostname -f

If your Ubuntu server doesn’t have an FQDN yet, you can use hostnamectl to set one.

sudo hostnamectl set-hostname your-fqdn

A common FQDN for mail server is You need to log out and log back in to see this change at the command prompt.

Set Up DNS Records for Your Mail Server

You need to go to your DNS hosting service (usually your domain registrar like NameCheap) to set up DNS records

MX record

An MX record tells other MTAs that your mail server is responsible for email delivery for your domain name.

MX record    @ 

A common name for the MX host is You can specify more than one MX record and set priority for your mail servers. A lower number means higher priority. Here we only use one MX record and set 0 as the priority value. (0 – 65535)

Note that when you create the MX record, you should enter @ or your apex domain name in the name field like below. An apex domain name is a domain name without any sub-domain.

email server MX record

A record

An A record maps an FQDN to an IP address.        <IP-address>

AAAA record

If your server uses IPv6 address, it’s also a good idea to add AAAA record for        <IPv6-address>

Hint: If you use Cloudflare DNS service, you should not enable the CDN (proxy) feature when creating A and AAAA record for Cloudflare does not support SMTP or IMAP proxy.

PTR record

A pointer record, or PTR record, maps an IP address to an FQDN. It’s the counterpart to the A record and is used for reverse DNS (rDNS) lookup.

Reverse resolution of IP address with PTR record can help with blocking spammers. Many MTAs accept email only if the server is really responsible for a certain domain. You should definitely set a PTR record for your email server so your emails have a better chance of landing in the recipient’s inbox instead of the spam folder.

To check the PTR record for an IP address, you can use the following command.

dig -x <IP> +short


host <IP>

PTR record isn’t managed by your domain registrar. It’s managed by the organization that gives you an IP address. You get IP address from your hosting provider, not from your domain registrar, so you must set PTR record for your IP address in your hosting provider’s control panel. Its value should be your mail server’s hostname: If your server uses IPv6 address, then 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 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.

Note: Gmail will actually check the A record of the hostname specified in the PTR record. If the hostname resolves to the same IP address, Gmail will accept your email. Otherwise, it will reject your email.

After all of the above is done, let’s play with Postfix.

Installing Postfix

On your ubuntu server, run the following two commands.

sudo apt-get update

sudo apt-get install postfix -y

You will be asked to select a type for mail configuration. Normally, you will want to select the second type: Internet Site.

build your own email server with postfix

  • No configuration means the installation process will not configure any parameters.
  • Internet Site means using Postfix for sending emails to other MTAs and receiving email from other MTAs.
  • Internet with smarthost means using postfix to receive email from other MTAs, but using another smart host to relay emails to the recipient.
  • Satellite system means using smart host for sending and receiving email.
  • Local only means emails are transmitted only between local user accounts.

Next, enter your domain name for the system mail name, i.e. the domain name after @ symbol. For example, my email address is [email protected], so I entered for the system mail name. This domain name will be appended to addresses that don’t have a domain name specified. Note that if you enter a sub-domain like, you will be able to receive emails destined for addresses, but not be able to receive emails destined for addresses.

build your own email server with postfix

Once installed, Postfix will be automatically started and a /etc/postfix/ file will be generated. Now we can check Postfix version with this command:

postconf mail_version

On Ubuntu 22.04, the Postfix version is 3.6.4, and Ubuntu 20.04 ships with version 3.4.10.

mail_version = 3.6.4

The ss (Socket Statistics) utility tells us that the Postfix master process is listening on TCP port 25.

sudo ss -lnpt | grep master

ubuntu postfix TCP port 25

Postfix ships with many binaries under the /usr/sbin/ directory, as can be seen with the following command.

dpkg -L postfix | grep /usr/sbin/



Open TCP Port 25 (inbound) in Firewall

The inbound TCP port 25 needs to be open, so Postfix can receive emails from other SMTP servers. Ubuntu doesn’t enable a firewall by default. If you have enabled the UFW firewall, you need to open port 25 (inbound) with the following command.

sudo ufw allow 25/tcp

Then we can scan open ports on the mail server with an online port scanner. Enter your mail server’s public IP address and select scan all common ports.

build your own email server redhat

You can see from the above screenshot that TCP port 25 is open on my mail server.

Checking If TCP Port 25 (outbound) is blocked

The outbound TCP port 25 needs to be open, so Postfix can send emails to other SMTP servers. The outbound TCP port 25 is controlled by your hosting provider, we can install the telnet utility to check if it’s open or blocked.

sudo apt install telnet

Run the following command on your mail server.

telnet 25

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

Connected to
Escape character is '^]'.
220 ESMTP y22si1641751pll.208 - gsmtp

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

Trying 2607:f8b0:400e:c06::1a...
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 the outbound port 25 for you. If they refuse your request, you need to set up SMTP relay to bypass port 25 blocking or use a VPS like Kamatera that doesn’t block port 25.

Some folks might be asking, “Can I change port 25 to another port to bypass blocking”? The answer is no. Changing the port works only when you control both the server-side and client-side. When Postfix sends emails, it acts as the SMTP client. The recipient’s mail server acts as the SMTP server. You don’t have control over the receiving SMTP server. SMTP servers are listening on port 25 to receive emails. They expect SMTP clients to hit port 25. There’s no other port for receiving emails. If your Postfix don’t connect to port 25 of the receiving SMTP server, you won’t be able to send emails.

Sending Test Email

As a matter of fact, we can now send and receive email from the command line. If your Ubuntu server has a user account called user1, then the email address for this user is [email protected]. You can send an email to root user [email protected]. You can also send emails to Gmail, yahoo mail or any other email service.

When installing Postfix, a sendmail binary is placed at /usr/sbin/sendmail, which is compatible with the traditional Sendmail SMTP server. You can use Postfix’s sendmail binary to send a test email to your Gmail account like this:

echo "test email" | sendmail [email protected]

In this simple command, sendmail reads a message from standard input and make “test email” as the message body, then send this message to your Gmail account. You should be able to receive this test email in your Gmail inbox (or spam folder). You can see that although we didn’t specify the from address, Postfix automatically append a domain name for the from address. That’s because we added our domain name in system mail name when installing Postfix.

Note: The From: domain name is determined by the myorigin parameter in Postfix, not by the myhostname parameter.

You can try to reply to this test email to see if Postfix can receive email messages. It’s likely that emails sent from your domain are labeled as spam. Don’t worry about it now. We will solve this problem in later parts of this tutorial series.

The inbox for each user is located at /var/spool/mail/<username> or /var/mail/<username> file. If you are unsure where to look for the inbox, use this command.

postconf mail_spool_directory

The Postfix mail log is stored at /var/log/mail.log.

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 open the mail log (/var/log/mail.log) with a command-line text editor, such as Nano.

sudo nano /var/log/mail.log

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

host[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 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, then you should also set PTR record for your IPv6 address. (PTR record is managed by the organization that gives you an IP address.)

To save a file in Nano text editor, press Ctrl+O, then press Enter to confirm. To exit, press Ctrl+X.

Using the mail program to Send and Read Email

Now let’s install a command-line MUA (mail user agent).

sudo apt-get install mailutils

To send email, type

mail -a [email protected]
user@mail:~$ mail -a FROM:[email protected] [email protected]
Subject: 2nd test email
I'm sending this email using the mail program.

Enter the subject line and the body text. To tell mail that you have finished writing, press Ctrl+D and mail will send this email message for you.

To read incoming emails, just type mail.


Here’s how to use the mail program to manage your mailbox.

  • To read the first email message, type 1. If only parts of the message is displayed, press Enter to show the remaining part of the message.
  • To display message headers starting from message 1, type h.
  • To show the last screenful of messages, type h$ or z.
  • To read the next email message, type n.
  • To delete message 1, type d 1.
  • To delete message 1, 2 and 3, type d 1 2 3.
  • To delete messages from 1 to 10, type d 1-10.
  • To replay to message 1, type reply 1.
  • To exit out of mail, type q.

Messages that have been opened will be moved from /var/mail/<username> to /home/<username>/mbox file. That means other mail clients can’t read those messages. To prevent this from happening, type x instead of q to exit out of the mail.

How To Increase Attachment Size Limit

By default, the attachment cannot be larger than 10MB, which is indicated by the message_size_limit parameter.

postconf | grep message_size_limit


message_size_limit = 10240000

This parameter defines the size limit for emails originating from your own mail server and for emails coming to your mail server.

To allow attachment of 50MB in size, run the following command.

sudo postconf -e message_size_limit=52428800

When postconf command is invoked with the -e (edit) option, it will try to find the parameter (message_size_limit) in the Postfix main configuration file (/etc/postfix/ and change the value. If the parameter can’t be found, then it adds the parameter at the end of the file.

Note that the message_size_limit should not be larger than the mailbox_size_limit, otherwise Postfix might not be able to receive emails. The default value of mailbox_size_limit is 51200000 bytes (about 48MB) in the upstream Postfix package. On Ubuntu, the default value is set to 0, as can be seen with

postconf | grep mailbox_size_limit


mailbox_size_limit = 0

This means that the mailbox has no size limit, which is great.

Restart Postfix for the changes to take effect.

sudo systemctl restart postfix

When sending an email with large attachments from your mail server, you should also beware of the receiving server’s attachment size limit. For example, You can not send an attachment larger than 25MB to a Gmail address.

Setting the Postfix Hostname

By default, Postfix SMTP server uses the OS’s hostname. However, the OS hostname might change, so it’s a good practice to set the hostname directly in Postfix configuration file. Open the Postfix main configuration file with a command-line text editor, such as Nano.

sudo nano /etc/postfix/

Find the myhostname parameter and set as the value. It’s not recommended to use the apex domain as myhostname. Technically you can use the apex domain, but it will create problems in later parts of this tutorial series.

myhostname =

Save and close the file. (To save a file in Nano text editor, press Ctrl+O, then press Enter to confirm. To exit, press Ctrl+X.) Restart Postfix for the change to take effect.

sudo systemctl restart postfix

Creating Email Alias

There are certain required aliases that you should configure when operating your mail server in a production environment. You can add email alias in the /etc/aliases file, which is a special Postfix lookup table file using a Sendmail-compatible format.

sudo nano /etc/aliases

By default, there are only two lines in this file.

# See man 5 aliases for format
postmaster: root

The first line is a comment. The second line is the only definition of an alias in this file. The left-hand side is the alias name. The right-hand side is the final destination of the email message. So emails for [email protected] will be delivered to [email protected]. The postmaster email address is required by RFC 2142.

Normally we don’t use the root email address. Instead, the postmaster can use a normal login name to access emails. So you can add the following line. Replace username with your real username.

root:   username

Ubuntu Postfix email alias

This way, emails for [email protected] will be delivered to [email protected]. Now you can save and close the file. Then rebuild the alias database with the newaliases command

sudo newaliases

Using IPv4 Only

By default, Postfix uses both IPv4 and IPv6 protocols, as can been seen with:

postconf inet_protocols


inet_protocols = all

If your mail server doesn’t have a public IPv6 address, it’s better to disable IPv6 in Postfix to prevent unnecessary IPv6 connections. Simply run the following command to disable IPv6 in Postfix.

sudo postconf -e "inet_protocols = ipv4"

Then restart Postfix.

sudo systemctl restart postfix

Upgrading Postfix

If you run sudo apt update, then sudo apt upgrade, and the system is going to upgrade Postfix, you might be prompted to choose a configuration type for Postfix again. This time you should choose No configuration to leave your current configuration file untouched.

postfix no configuration

Next Step

Congrats! Now you have a basic Postfix email server up and running. You can send plain text emails and read incoming emails using the command line. In the next part of this tutorial series, we will learn how to install Dovecot IMAP server and enable TLS encryption, which will allow us to use a desktop mail client like Mozilla Thunderbird to send and receive emails.

As always, if you found this post useful, subscribe to our newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial
[Total: 174 Average: 4.8]

172 Responses to “Build Your Own Email Server on Ubuntu: Basic Postfix Setup

  • Great article…looking forward to the second part of it.

  • Joe Genshlea
    8 years ago

    I’m looking to setup postfix on ubuntu 16.04 to simply relay a message to the gmail smtp server. Will that be discussed?

    • Xiao Guoan (Admin)
      8 years ago

      To forward emails, simply create a .forward file in the user’s home directory, then enter the destination email address in the .fowared file.

      If you installed Roundcube, you can also create a filter in Roundcube to redirect messages to another email address.

  • Julio Cesar Sanders
    8 years ago

    Very good !!

  • In which config file ??? thats not clear here !
    Set up DNS Records for Your Mail Server
    MX record

    An MX record tells other MTAs that your mail server is responsible for email delivery for your domain.

    MX record @

    A common name for a mail host is You can specify more than one MX record and set priority for your mail servers. A lower number means higher priority.
    A record

    An A record maps a FQDN to an IP address.

    • Xiao Guo-An (Admin)
      6 years ago

      Hi Toco, you need to go to your DNS hosting service (usually your domain registrar) to set up DNS records.

  • James Young
    6 years ago

    I’m having a lot of difficulty setting up an email server, because in /var/log/mail.log I always get messages like this:

    Sep 12 17:35:30 instance-1 postfix/smtp[19741]: connect to[2607:f8b0:400c:c02::1b]:25: Network is unreachable
    Sep 12 17:35:33 instance-1 postfix/smtps/smtpd[19735]: disconnect from[x.x.x.x] ehlo=1 auth=1 mail=1 rcpt=1 data=1 quit=1 commands=6
    Sep 12 17:35:35 instance-1 dovecot: imap-login: Login: user=, method=PLAIN, rip=x.x.x.x, lip=, mpid=19743, TLS, session=
    Sep 12 17:36:00 instance-1 postfix/smtp[19741]: connect to[]:25: Connection timed out
    Sep 12 17:36:00 instance-1 postfix/smtp[19741]: connect to[2a00:1450:400c:c06::1a]:25: Network is unreachable
    Sep 12 17:36:00 instance-1 postfix/smtp[19741]: connect to[2a00:1450:400b:c01::1a]:25: Network is unreachable
    Sep 12 17:36:10 instance-1 dovecot: imap(james@mysite): Logged out in=30633 out=1715

    As far as I know, I’ve got the setup alright. I use MySQL and have virtual domains and virtual users. It seems to work fine and the test commands all work out.

    But now I get to the point where I set up Outlook at home, and add my new IMAP account. mail.mysite:993 and mail.mysite:465. This adds the account and a message from Outlook is dropped in /var/mail/.

    But when I go to send email from Outlook, which should go to my server and get passed on, I keep getting blocked. It must be the port 25 it’s trying to reach another server on. I don’t know really, that’s my guess. I want the mail server to connect and e.g. deliver mail over SSL/TLS to the recipient email server on port 465 or 587. How do I get this working, so my mail server will accept mail from me and deliver it?

    I’ve googled for hours and I’m making absolutely no progress!

    • Xiao Guo-An (Admin)
      6 years ago

      Hi James,

      This following message in your mail log indicates port 25 is blocked.

      connect to[]:25: Connection timed out

      You can set up Postfix SMTP relay to bypass port 25 blocking.

  • Much appreciated. Well written article.

  • Thank you for the great article explaining what goes into an end-to-end email server. I am using mine now on Ubuntu 18.10.

  • Gerry
    5 years ago

    Great article. What would be useful too is how to set up specific email addresses to RECEIVE mail on the server. All the articles I’ve found deal with sending mail… which I can do, but when I try and send from gmail > myServer, I get “550 5.7.1 Relaying denied” email response ( ? )

  • Raymond Wu
    5 years ago

    Thank you for putting all these together. Very helpful!!!!!

  • Shibasis Patel
    5 years ago

    The first time I tried, it worked and I got a mail in my spam folder. The next time I tried, it didn’t send my email and said:

    1] Our system has detected an
        550-5.7.1 unusual rate of unsolicited mail originating from your IP
        address. To 550-5.7.1 protect our users from spam, mail sent from your IP
        address has been 550-5.7.1 blocked. Please visit 550-5.7.1 to review our 550
        5.7.1 Bulk Email Senders Guidelines. q2si5578154pgd.28 - gsmtp (in reply to
        end of DATA command)
    • Xiao Guo An (Admin)
      5 years ago

      It’s pretty clear that your IP address had been used to send spam (aka unsolicited bulk email).

      To solve this problem,

      First, stop spam from your server.

      Then, you can try sending email to your own Gmail account a few times to create good user engagement: If the email land into spam folder, mark it as not spam. You should send emails back and forth several times.

      After that, the Gmail rate limiting will gradually be relaxed and finally disappear.

      A better approach is using a hosting provider that has high IP reputation. We recommend Kamatera: How to Create a Linux VPS Server on Kamatera

      You can also set up SMTP relay so that Gmail cannot check your mail server’s IP address.

  • Auditor R.
    5 years ago

    Followed all the tutorial parts, everything is good and working.
    Learned a lot by doing from scratch. Big Thanks.
    Got one question. How can i add other domains, ex: [email protected], [email protected] ?

  • torvan
    5 years ago

    5 star writing! Very clear and informative and plain language for understanding. One shot then started as smoothly as expected. Continue learning Part 2 and Part 3.

  • G.R.Regis
    5 years ago

    I’ve alway heard that setting up your own email server with postfix and dovecot was a terrible pain and it was just best to use something like iRedmail or Modoboa if you wanted to host your own. I’ve tried in the past using various tutorial and gave up used those other packages for a while. After being my go to for linux guides because they are always so easy to follow and just work, I decided to try Linuxbabe’s Postfix/Dovecot tutorial series (on Debian 10 instead) and it was a breeze. I highly recommend this entire series and any other tutorial on this site.

    • Xiao Guoan (Admin)
      4 years ago

      Hi G.R.Regis,

      Thanks for your comment.

      I just published a new tutorial showing how to create virtual mailboxes with PostfixAdmin, which is an open-source web-based interface to manage mail domains and users, so you can use Maildir format, easily create virtual users and aliases.

      • G.R.Regis
        4 years ago

        I’ve done that tutorial too now, and once again it worked nicely. I had a couple hiccups along the way, but that was probably because I was doing it in a Docker container so if I need to reinstall my server or migrate it, it’ll be easy to keep everything without have to deal with migrating databases.

  • Nathaly
    5 years ago

    Sorry for my bad English, I’m French and I use google translate.
    Super tutorial very well explained. Too bad he just use the Mbox format. Indeed, it is not very practical to have to create an account on the server for each email address without speaking that we can not, if I’m not mistaken, make aliases. (For example, to [email protected] and [email protected] in the container [email protected]).
    Do you want to follow this tutorial using the Maildir format?
    Otherwise, is it difficult to adapt this tutorial to switch to Maildir format and use MySQL to create postfix accounts?
    In any case, thank you again for this great tutorial!

  • itsmesri
    4 years ago

    IS this works for iRedmail server too? I think I need to implement this.

    • Xiao Guoan (Admin)
      4 years ago

      If you use iRedMail, then you don’t need to follow this tutorial. iRedMail is a shell script that automatically installs and configures mail server components for you.

      This tutorial series shows you how to manually set up a mail server.

      • Srikanth
        4 years ago

        I am talking about Part 4 – 6 for SPAM and DKIM

    • Xiao Guoan (Admin)
      4 years ago

      I have already talked about SPF, DKIM, DMARC in the iRedMail tutorial. If you follow the instructions you are good to go.

      iRedMail ships with spam filters in the Postfix configuration file, so you don’t need to follow the blocking spam with Postfix tutorial.

  • Ken Wright
    4 years ago

    I’ve been following your instructions here, but I’d rather set up Postfix to use virtual users. Is there a way to do this?

    • Xiao Guoan (Admin)
      4 years ago

      You will learn how to do that in part 3. Be sure to complete part 1 and part 2 before reading part 3.

  • Masood Arif
    4 years ago

    Hey my college assignment is to make email server i found this one but i’m confused that is it a GUI based email server or just terminal based, waiting for your kind response.

    • Xiao Guoan (Admin)
      4 years ago

      The first part is just for command line. You will learn how to use GUI to interact with your mail server in part 2 and part 3.

  • Hello thank you so much for this wonderful tutorial.
    I have challenges though,…
    I have setup a live website on the main domain ( In this tutorial you say that we use as the hostname for mail hosting. You also state that we should set the DNS at the hosting company. So far thankfully very clear. Except am confused because the DNS for is the same as DNS for This has made it really hard to figure things out because:
    1). The current hostname is while you said it should be
    QUESTION: Should I change the hostname from to
    2). Setting up TLS encryption has challenges because, again, it’s the same domain name.

    Further, I went ahead and created another server for mail hosting but again encryption won’t work because of share base domain but with a different IP address.

    Main question:
    How would you structure having a main domain name ( and wanting an email setup( Do they all go to the same server (eg Digital ocean droplet)?

    • Xiao Guoan (Admin)
      4 years ago

      If you set the hostname in the Postfix main configuration file (/etc/postfix/, then you don’t need to change the OS hostname.

      You can have multiple virtual host files in Apache or Nginx to host multiple domain names (, If you follow the instructions in the article, you should have no problem in enabling TLS encryption.

  • Jonathan
    4 years ago

    First page… it says hostnamectl set-hostname will set your machine hostname… and it does but, when I type hostname –long or hostname -f, all I get is Not, which was set by hostnamectl. I’ve confirmed it is set correctly by typing just hostname, by itself. Any idea why the –long or -f command wouldn’t work properly?

    • Xiao Guoan (Admin)
      4 years ago

      I don’t know, but you can set the hostname directly in Postfix, so the OS hostname won’t be used.

      sudo postconf

      Then restart Postfix.

      sudo systemctl restart postfix
    • saleem
      4 years ago

      Just check in the /etc/hosts file. Probably the order is backwards; it should read the fqdn first and then the local hostname on the line that has both. You can just switch them and save the file and it will be fine.

      • Jonathan
        4 years ago

        I went back to verify this when I got the email and I found this…       localhost       localhost.myotherdomaincom

        obviously I’ve substitued actual IPs for 254,253,252 but you can see that it’s still backwards. However, if I type hostname now, it comes up with… which is strange. I think it stopped returning the fqdn incorrectly when I edited my host file directly, adding

    • Xiao Guoan (Admin)
      4 years ago

      You should put the hostnames on the same line for the same IP address, and should be placed before localhost. localhost
  • – This series of articles are EXCELLENT for anyone who want or need to have a dedicated email server.

    – Thank You so much for this great content.

  • aakash
    4 years ago

    hi Xiao,

    I am new to the idea of email server setup I wanted to understand the logic to create a FQDN
    i have a ubuntu machine with machine name as mb and my domain from go daddy is
    then what should be my FQDN or or

    please help me in understanding the actual logic for FQDN.

    • Xiao Guoan (Admin)
      4 years ago

      An FQDN is a hostname plus your apex domain name. A common FQDN for mail server is When you change the FQDN, your hostname also changes. It couldn’t be simpler.

  • Once again, this really is a fantastic series – thank you so much. I’m very close to having a great email server – getting an almost perfect score on My struggle is the PTR record for reverse DNS. I’m using AWS for everything. My mail server is an EC2 instance, with a public IP and also a public domain assigned by AWS (, where the Xs represent the IP address). Currently, mail-tester reports the following:

    Your IP address XX.XXX.XX.XX is associated with the domain
    Nevertheless your message appears to be sent from

    (I’ve changed my domain and IP address).

    So far, I’ve created a PTR record as described here:

    I’ve also had a little play with a CNAME record.

    If anyone has any tips that would be greatly appreciated. Many thanks in advance.

    • expert
      4 years ago

      This changed in AWS since Jan Feb 2020, you need to make a request, there is no other way to fix this. Mine took 2 days to complete. Search for the form.

      • Thank you for your response. You’re right – I filled out a form called “Request to remove email sending limitations” and after a few days, the reverse DNS came back with Thanks very much.

  • Colin Parkinson
    4 years ago

    Hi All
    Can I change the port from 25 to 465 to get around the port blocking of port 25 ??
    Regards to all

    • Xiao Guoan (Admin)
      4 years ago


      To send an email, your SMTP server needs to hit the port 25 of the receiving SMTP server. The receiving email server expects you to hit port 25. There’s no other port for receiving email.

      This is like how web server works. Web servers are listening on port 80 and 443. Web browsers need to hit one of the two ports in order to download web pages.

      In the email world, there’s only one port for SMTP servers to receive email and it’s port 25. Port 465 (SMTPS) is used by mail clients to submit outgoing emails to your own email server. It’s not for sending email from one SMTP server to another SMTP server.

      • Colin
        4 years ago

        Hi Xiao
        My apology to contradict you, but most of our email servers in NZ block port 25 as this is susceptible to spamming.
        Our current email server uses port 465 to avoid this and our email clients (local PC) send outgoing email to this server using port 465. (example =

        • This must be why I don’t get many emails from NZ 🙂

          When receiving email from some email client software, you can use port 465. When your email server talks to another email server, if you don’t use port 25, you’re not going to get very far with most of them.

    • Xiao Guoan (Admin)
      4 years ago

      I think your original question is: If the port 25 (outbound) on the email server is blocked, can Postfix use port 465 to send emails to other SMTP servers? The answer is no.

      Sending emails from one SMTP server to another SMTP server is not the same as sending outgoing emails from email clients to your own email server.

      Email clients can always use port 465 to submit outgoing emails to your own email server.

      The outbound port 25 in this article refers to the port on the email server. It’s not the outbound port 25 on email clients. Actually, it’s unusual these days to use port 25 on email clients to submit outgoing emails to your own email server. It’s common to use port 587 or 465 to submit outgoing emails.

    • Xiao Guoan (Admin)
      4 years ago

      “Our current email server uses port 465 to avoid this “. Are you referring to using port 465 to submit outgoing emails to an SMTP relay service? This article has already stated that you can use SMTP relay to bypass port 25 blocking.

      If you are referring to using port 465 to send emails from your mail server directly to the recipients. Your emails are not likely to reach the recipient.

  • Hey,

    thank you for these great tutorials!

    Just two questions:
    – what script/technique/program would you recommend to poll multiple mailboxes from a webhoster like (especially so called catch-all mailboxes) and then transmit the polled emails to this mailsystem with postfix and dovecot, sorting the emails in corresponding virtual mailboxes?

    – will there be any enhancement for this great tutorials to integrate things like spam-filter, virus-filter, sieve, … ?

    Best regards, Alex

    • Just to clarify: I run this setup as a non-internet facing, local mailserversystem, sending outbound mails through postfix configured for relaying over my ISPs mailserver…

    • Xiao Guoan (Admin)
      4 years ago

      There’s a program called fetchmail that can transmit mailboxes, but I’m not sure if it can work with catch-all mailboxes and sort the emails. Perhaps you can also download all your emails in Mozilla Thunderbird, then change your mail server hostname and re-sync the emails to your new mail server.

      Spam-filter is discussed in part 8 and part 9 in this tutorial series.
      Sieve filter is explained in the Roundcube article.

      I haven’t published a separate tutorial for virus filter yet, I will add it in my to-do list. However, many emails containing viruses can be blocked by the spam filters in my articles.

      • Thank you for your reply!
        ATM I’m using getmail to poll the external mailserver of my webhoster. getmail works with catchall mailboxes but someone has to feed the fetched emails to postfix again _not_ to dovecot directly, otherwise the alias addresses are not expanded and delivered correctly.

        But in the meantime I discovered another problem: Thunderbird supplies wrong From: and To: addresses when clicking “Reply”. Thunderbird wants me to send the reply-email in the name of the initial sender (which I am not) to my own alias (which makes no sense).

        If I check the source code of the eMail, the From, To, Envelpe-To seems to be correct in my understanding.

        I wrote a post within stackoverflow, but no one can help, can you?

        Thank you for your tutorials and your help!

  • Diego
    4 years ago

    Hi Xiao. Thanks a lot for your job, REALLY! I love to learn new things and this is just great stuff.

    Xiao, I can see you have a lot of tutorials for configuring a Mail Server. I’m a bit lost. I’m kind of newbie with mail servers.

    Where to start?

    What can you tell about using sendmail? I mean, I have a LEMP stack VPS for WordPress (Ubuntu 18.04). The way I’ve been managing the SMTP for my WordPress installations is :

    sudo apt-get update && sudo apt-get install sendmail

    Just made a Postfix installation for 1 VPS but with someone help, not on my own. And I want to use Mautic too, so I want to go further and apply everything I’ve been just reading from you since like 8 months ago.

    Does it make sense to you for me to ask you where should I start? Is this post the first step to follow?

    Thank you so much.

    • Xiao Guoan (Admin)
      4 years ago

      Yes, you should start with this post.

      It’s not recommended to install the traditional sendmail package. It’s hard to configure. Remove it with:

      sudo apt purge sendmail
  • Guy Merritt
    4 years ago

    I set up Postfix, as a test, about 2 months ago. I had been using Qmail for years. Postfix was working fine, from the local box. Thunderbird connected and worked, etc. I now have two installs, on two different boxes, and Thunderbird cannot send mail from the other server. In other words, if I have on my computer (testing Postfix) sending mail does not work from another computer when trying to use My logs say: NOQUEUE: reject: RCPT from unknown. What configuration do I need so that a different computer can send mail from my server. Both of my test installations (different domains) exhibit the same behavior. If I am sitting at the computer which has the server installed, I can send mail – other machines cannot connect and use it to send mail.

  • Guy Merritt
    4 years ago

    Ignore my previous comment – I did some reading and got things working, on other boxes, using SASL.

  • Marcus Bahn
    4 years ago

    Thank you very much!
    It’s the best tutorial i have ever seen! It helped so much to understand a mail-server!
    The tutorial works on two different vps…


  • Robert Tang-wai
    4 years ago

    Hi Xiao,

    Excellent series of tutorials on setting up email services, I have tried this in the past with little success but your instructions are quite a bit clearer and detailed than the documentation I previously referenced.

    I am hosting my own Ubuntu 20.04 server (on a Hyper-V 2019 VM), my ISP blocks port 25 so I had to set up SMTP relay. I have that working so I can send email out just fine, but for some strange reason I cannot receive external email. I can email internally between accounts on the Ubuntu server so that isn’t completely broken.

    I use pfSense as my router/firewall, I confirm I am forwarding ports 25, 80, 143, 443, 465, 587, and 993 to my Ubuntu server (it also hosts my WordPress blog and Nextcloud Hub). Ubuntu itself is not running the internal firewall.

    I confirm the MX and A records are in place with my DNS registrar.

    Any suggestions? I was under the impression that getting send email to work was harder than receive, not the other way around.

    Thanks in advance!


    • Xiao Guoan (Admin)
      4 years ago

      Maybe you should tell me your domain name, so I can debug? If you don’t want to show your domain name in public, then reply to my email.

    • Xiao Guoan (Admin)
      4 years ago

      I tried to send an email to your domain. Here’s my Postfix log.

      connect to[xx.xx.xx.xx]:25: Connection timed out

      This indicates there’s a firewall preventing my mail server from connecting to the port 25 of your mail server.

      • Robert A Tang-wai
        4 years ago

        I just finished speaking with my ISP, they block port 25 traffic *BOTH* ways. I’ll have to get a store/forward service. Thanks for the help!

  • Randall
    4 years ago

    Regarding aliases, is it possible to set up an alias to send postmaster and root mail to an address off the server? For example, I administer several servers and I’d prefer any emails to postmaster or root to come to my gmail account. Is that possible?

    4 years ago

    After setup Postfix i can send test e-mail:

    echo "test email" | sendmail [email protected]

    but this command not work for me:

    mail [email protected]

    Probably mailutils is not configured and is sending from different DNS – google bouncing email with reject:

    Our system has detected that this 550-5.7.1 message does not meet IPv6 sending guidelines regarding PTR records 550-5.7.1 and authentication.

    What about Virtual Hosts in one VPS? How to configure all emails for all domains?

    • Xiao Guoan (Admin)
      4 years ago

      The Gmail reject message tells you to set PTR record for your IPv6 address.

      You will learn how to host multiple domains (virtual hosting) on a single VPS in part 7 of this tutorial series.

      • MESSIAH
        4 years ago

        Thanks. Done and work like in your tutorial.

  • Hi Xiao
    Great tutorials, first of all!
    I am just going through now.
    need some light, anyway:
    I set up few accounts by inserting manualy into mysql a username and an encrypted passwd.
    How can I create new accounts without typing into mysql?
    How can I recover or change a password?

    4 years ago
    hostname -f

    Give me this output:

    How I should setup DNS and hostname for installation dovecot and postfix?
    Is this correct?
    • Xiao Guoan (Admin)
      4 years ago

      Set your hostname to
      • MESSIAH
        4 years ago

        I can’t use just as hostname?

    • Xiao Guoan (Admin)
      4 years ago

      You can, but if you mess up your mail server in the later parts of this tutorial series, you are on your own 🙂

    4 years ago

    How I can setup rDNS and PTR for multiple Virtual Hosts? I have only one IPv4 IP and 3 IPv6 IPs

    • Xiao Guoan (Admin)
      4 years ago

      You need to set rDNS to the Postfix hostname only once. There’s no need to change the rDNS when you add additional virtual hosts later.

      • MESSIAH
        4 years ago

        It will be work if I set my only one IPv4 to not a If this is not possible can I use 1 of 3 my IPv6 to

    • Xiao Guoan (Admin)
      4 years ago

      If your postfix hostname is, then set the rDNS to
      If your postfix hostname is, then set the rDNS to

      As I have said earlier, using is a good practice. Using as the hostname will likely to get you in trouble.

    4 years ago

    Hello guys,

    Spent quite some time on some issues i had, turned out that my IMAP Inbox was being empty while with mail command i could see the mails in my Inbox.

    There is a missing line in /etc/postfix/

    home_mailbox = Maildir/

    This sets inbox to Maildir/ which is set to be home mailbox in Dovecot. Without this, your Inbox in whichever client youre using (webmail, mozilla, outlook) will be empty.


  • nilton
    4 years ago

    When using (nmap your-server-ip) on another pc it does not show port 25. When using (telnet 25), it shows that the outgoing port is ok.

    What do you think?

    • Xiao Guoan (Admin)
      4 years ago

      The nmap command checks if the inbound port 25 of your mail server is open. This is for your mail server to receive emails.

      The telnet command checks if the outbound port 25 of your mail server is open. This is for your mail server to send emails.

      If the nmap command didn’t show the inbound port 25, there might be another firewall sitting in front of your server.

  • Angel
    4 years ago

    FQDN is the same that why are you using mail… instead www .

    • Xiao Guoan (Admin)
      4 years ago

      Because mail makes it easy for you to identify what services this sub-domain provides.

      www is for web services (a website for visitors to browse), right?

  • Pawel
    4 years ago

    Thanks a lot for your tutorial. I just started to go through your articles. A little concern I have is regarding any graphical or (in red color) comments since they are not accessible for a blind, screen reader users. I’ll contact you back if get in any difficulties.

  • Hi, how do you know the email address you claim in step 1ish is not already taken? Postfix doesn’t warn you if it is.

  • Thanks for the tutorial. I’m not sure it worked. It’s very esoteric language and I’m sure it’s easy enough to understand if you pore over it for weeks on end. So, in simple terms: Not very simple. Tedious if you opt for tedium.

    But it did get me started. What can I say. Your tutorial is the first one that showed up after I realized I needed a professional email address for my career. Thanks for being there, I love your website/blog, and keep up the good work.

    4 years ago
    root@mailserver:~# sudo systemctl status postfix
    ● postfix.service - Postfix Mail Transport Agent
       Loaded: loaded (/lib/systemd/system/postfix.service; enabled; vendor preset: enabled)
       Active: active (exited) since Sun 2020-07-19 00:38:38 UTC; 1min 26s ago
      Process: 4374 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
     Main PID: 4374 (code=exited, status=0/SUCCESS)
    Jul 19 00:38:38 systemd[1]: Starting Postfix Mail Transport Agent...
    Jul 19 00:38:38 systemd[1]: Started Postfix Mail Transport Agent.

    Why status Active: active (exited) Xiao? Thanks

    • Xiao Guoan (Admin)
      4 years ago

      This is normal. If you open the /lib/systemd/system/postfix.service file, you will see that the Postfix systemd service is a oneshot service. Postfix will run the master process after the main Postfix process exits.

  • James
    4 years ago

    Many thanks for this comprehensive guide, I now have multiple domains setup and its very professional.

    One thing though, for development/testing, I need to telnet into my mail server on port 25, but this seems to be blocked, but i dont have a firewall enabled. How can I allow telnet to port 25, which seems to be industry standard?

    • James
      4 years ago

      Note. My understanding is that port 25 must remain open, as this how emails get sent between servers, another mail server will connect on port 25 of my server, so it can deliver the message.

    • Xiao Guoan (Admin)
      4 years ago

      If you telnet from your local computer to your mail server on port 25 and its blocked, it indicates your local firewall (maybe your local ISP) is blocking outbound traffic on port 25.

      • James
        4 years ago

        It did not occur to me thanks, even though I can telnet to on 25, other mail servers I can’t, so yeah it must be ISP. thanks.

  • mehdi
    4 years ago

    I’m just wondering if, after installing and configuring postfix, it is possible to receive emails from another domain like gmail for example or whatever domain and forward them to my gmail account ?

    • Xiao Guoan (Admin)
      4 years ago

      It’s possible. However, that will require another long tutorial.

  • Hello Xiao,

    there is one thing that i can’t see covered on all those parts and that is the “Unsubscribe link”. Can you help with?


    • Xiao Guoan (Admin)
      4 years ago

      You should use a mailing list manager like Mailtrain or Mautic to manage subscriptions.

      • Thank You so much.

        What If I have to choose one comparing with Mailchimp?

    • Xiao Guoan (Admin)
      4 years ago

      Mailtrain is designed to function like Mailchimp, and it’s easy to use.

      Mautic is not intuitive and has a learning curve.

  • Robert Herzog
    4 years ago

    I have the problem that my server does nos accept incoming email. I tend to believe that the problem comes from the master process does not listen to all IP addresses, only to (the localhost), as indicated by the output of netstat -lntp:

    tcp  0  0* LISTEN  14491/master

    while your example gives:

    tcp  0  0* LISTEN  1367/master

    Also a remote nmap does not show port 25 open
    How / what shall I change ?
    Thanks !

    • Xiao Guoan (Admin)
      4 years ago

      Edit /etc/postfix/ file and change the value of inet_interfaces to all.

      inet_interfaces = all

      Then restart Postfix.

  • Andre Rodrigues
    4 years ago

    Hi, amazing article, congratulations.

    I’m using sendgrid to send my email. I configured it through Exim.

    Its possible to replace the sendgrid to a server with postfix?

    Thank you very much

  • AnonymousWH
    4 years ago

    I can’t send me local emails so even 🙁

    proxmox@correo:~$ echo "mail body" | mail -s "test mal" root
    proxmox@correo:~$ echo "mail body" | mail -s "test mal" proxmox
    proxmox@correo:~$ mailq
    Mail queue is empty
    proxmox@correo:~$ mail
    Cannot open mailbox /home/proxmox/Maildir: Permission denied
    No mail for proxmox
    proxmox@correo:~$ sudo -s
    • Xiao Guoan (Admin)
      4 years ago

      By default, the mail command reads emails in the /var/spool/mail/ directory. Since you changed the mail_location, use the following command to scan emails in other directories.

      mail -f /home/proxmox/Maildir

      And you have a permission problem, check who owns the Maildir.

      ls -lh /home/proxmox/Maildir
  • Xiao, thank you for this article.

    All worked apart from the following questions:

    1) “Normally we don’t use the root email address. Instead, the postmaster can use a normal login name to access emails. So you can add the following line. Replace username with your real username.

    root: username”

    Do I add that in a new line underneath “postmaster: root”

    2) “If your mail server doesn’t have a public IPv6 address, it’s better to disable IPv6 in Postfix to prevent unnecessary IPv6 connections. Simply run the following command to disable IPv6 in Postfix.

    sudo postconf -e “inet_protocols = ipv4″”

    How do I find out if my IPv6 address is private or public?

    Thanks again for you help!

    • Xiao Guoan (Admin)
      4 years ago

      1.) Yes, add it underneath “postmaster: root”.
      2.) If you can ping your IPv6 address from another server that’s not on the same network, you have a public IPv6 address.

      • Thanks for the reply, much appreciated.

        I don’t have another server to test so skipped that part.

  • Prakash Raj
    4 years ago

    when i try to send mail to gmail server this error comes

    (delivery temporarily suspended: connect to[]:25: Connection timed out)
    [email protected]

    • Xiao Guoan (Admin)
      4 years ago

      That means port 25 (outbound) is blocked by your ISP.

      • Prakash Raj
        4 years ago

        how to unblock it. I’m using stand alone ubuntu server.

    • Xiao Guoan (Admin)
      4 years ago

      As I said in this article, 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.

      • Prakash Raj
        4 years ago

        How can i change port 25 to any other port?

    • Xiao Guoan (Admin)
      4 years ago

      You can’t. Even if you can, the recipient won’t receive your email, because their email servers are listening on port 25 for receiving emails.

      The receiving email server expects you to hit port 25. There’s no other port for receiving emails. If you don’t connect to port 25 of the receiving SMTP server, you won’t be able to send emails.

  • Prakash Raj
    4 years ago

    When i use

     sudo nmap  

    my system emits follwing what should i do

    Starting Nmap 7.60 ( ) at 2020-10-01 14:37 IST
    Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
    Nmap done: 1 IP address (0 hosts up) scanned in 3.18 seconds
    • Xiao Guoan (Admin)
      4 years ago

      It already told you what to do: use the -Pn flag.

      sudo nmap -Pn

      FYI: nmap is used to scan the inbound ports of your mail server, not the outbound ports.

    • Prakash Raj
      4 years ago

      Is sendinblue server is free or paid service?

    • Xiao Guoan (Admin)
      4 years ago

      You can use Sendinblue to send 9000 emails per month for free.

  • When I do host it says not found: 3(NXDOMAIN)

    I am using a VPS and in the dashboard changed the hostname to and rebooted server

    but still i get not found: 3(NXDOMAIN)

    But when when I ssh into my domain, the prompt is so I changed hostname to using sudo hostnamectl set-hostname

    but I still get not found: 3(NXDOMAIN)

    • Xiao Guoan (Admin)
      4 years ago

      Simply changing the hostname doesn’t affect the PTR record. Ask your VPS provider how to set PTR record.

  • Hi,

    I just wanted to say, that those articles are really great. I’m just setting up my third mailserver, this time in an automated manner, and I still haven’t found anything better than this series.

    One thing I’d like to mention though is, that the config breaks the apparmor profiles, which come with debian and ubuntu. I’ll fix them while writing my automation though, and in case you want to have the results, I can post them here.

    • I need to take back the offer of posting neccessary changes to the apparmor profiles. The postfix profiles work out of the box, and the dovecot profiles were removed in debian buster, and I suspect also in ubuntu 20.04.

  • Hi, i setup my server this one but im not received extarnal mail, do you know why?

    • Xiao Guoan (Admin)
      4 years ago

      Possible causes for unable to receive emails:

      1. Your MX record is wrong.
      2. Your mail server hostname doesn’t have DNS A record.
      3. Your firewall doesn’t allow incoming connection to port 25. Maybe your mail server is behind a NAT?
      4. Postfix isn’t listening on the public IP address.
      5. Check the mail log (/var/log/mail.log) to find out if there are other errors in your configuration.

      You can use the Network Tools Email Checker to test if your SMTP server is reachable from the Internet. Just enter your domain email address and click the Go button. As you can see from the screenshot below, it successfully found my domain’s MX record and my SMTP server is reachable from the Internet.

      email checker

      If your SMTP servers isn’t reachable from the Internet, then you have a problem in the first 4 items. If your SMTP server is reachable from the Internet, but you still can’t receive emails, check the mail log (/var/log/mail.log) to find out if there is any errors in your Postfix and Dovecot configuration.

  • Hello Xiao,
    Besides the “a long and tedious process” what are the Pros and Cons of each solution – “iRedmail” versus “email server from scratch” -?
    kindest regards,

  • Hi,
    just a question: mailboxes from my webhoster have an INBOX and all the special IMAP folders (Sent, Trash, …) are _subfolders_ of that INBOX. If I follow your tutorial, a mailbox has all its folders on the root level, so there are no subfolders of INBOX.

    What’s the benefit of doing it so or so? Can I change this afterwards to get the same layout like my webhoster has or will this destroy/corrupt the mailboxes which are already in use?

    Another interesting thing would be a configuration for shared/public mailboxes for office wide [email protected] mailboxes 🙂

    Thank you very much for this nice tutorials!

    • Xiao Guoan (Admin)
      4 years ago

      You will have all the usual INBOX, Sent, Trash, Spam folders when you complete part 2.

      • Yes the folder are there, but:


        Your setup:


        So in your setup the folders are not *subfolders*

    • Xiao Guoan (Admin)
      4 years ago

      Are you using mbox or maildir format for the mailbox?

    • Xiao Guoan (Admin)
      4 years ago

      Backup the original mail folder, then sync it to the new mail folder. For example, If you follow part 3, the maildir would be /var/vmail/

      sudo rsync -av --progress /home/xiao/Maildir/ /var/vmail/

      Then change the ownership to vmail user.

      sudo chown vmail:vmail /var/vmail/ -R
  • Gabriel
    4 years ago

    Hi, I have a question. If you place several identical servers on several different subdomains e.g., etc., will the configuration of the hostname setting differ from what you have presented in this entry ?

    • Xiao Guoan (Admin)
      4 years ago

      Just treat and like two different domains. will be the MX host for will be the MX host for

  • ScottyV
    4 years ago

    Hi, I hope you can shed a little light on this issue I am having.
    The hostname of my server set as ABC-123.
    I have edited /etc/postfix/ – “myhostname =” (NOTE: Not using
    When I send a test email, the “from” address shows as “[email protected]”.
    Q1 – Do I still need to rename my server to “”?
    Q2 – Does the “myhostname” setting in not fully override the server hostname for sending emails?

    • Gabriel
      4 years ago

      Thank you for your answer.

    • Xiao Guoan (Admin)
      4 years ago

      The From: domain name is determined by the myorigin parameter in Postfix.

      linuxbabe@mail:~$ postconf myorigin
      myorigin = /etc/mailname
      linuxbabe@mail:~$ cat /etc/mailname

      Note: You should set your hostname to Using as the hostname will cause problems when you follow part 3.

      • ScottV
        4 years ago

        Hi Xiao,
        Here is something interesting I discovered.
        (The server instance is still labeled as ABC-123.)

        When I send a test email via

        echo "test email" | sendmail [email protected]

        it lands in my inbox with the “From” field formatted as: [email protected].
        This is the result I expect.

        But, if I use

        mail [email protected]

        (from mailutils), it lands in my SPAM folder with the “From” field formatted as: root@ABC-123 (It used the server hostname)
        This is not what I expect.

        I am continuing to explore/research this issue.

        • ScottV
          4 years ago

          I have found an article that may be of interest:

          I have put this in place on my test box and it seems to be more what I would expect should happen.
          I still have a few more steps to complete before I move onto part #2.
          It will also be interesting to see what happens when I get to part #3.

        • Brandon
          3 years ago

          I’m running into this same issue Scott, were you able to get this sorted out? I browsed your link but it’s a little over my head.

        • ScottyV
          3 years ago


          Try setting things up this way:

          To use a local domain other than the hostname in Mailutils:

          Create a file /etc/mailutils.conf with the following contents:

          address {
  • Gabriel
    4 years ago

    Hi, I found this error in dovecot logs:

    `pam_unix(dovecot:auth): Couldn’t open /etc/securetty: No such file or directory`

    Do you know what it can be associated with ? In addition, when I set up an account with the Thunderbird client, I had a problem with the SSL certificate. The message said that the certificate was issued for and not for How can I resolve this?

  • Geronimo Stade
    3 years ago

    Hey! Perfect tutorial! Unfortunately i am having trouble and the Internet doesnt offer any solution.

    mail_version = 3.3.0
    Ubuntu 18.04

    When i start the server or restart postfix, postfix works without a problem.
    After a while:

    systemctl status postfix
    root@altair:~# systemctl status postfix
    ● postfix.service - Postfix Mail Transport Agent
       Loaded: loaded (/lib/systemd/system/postfix.service; enabled; vendor preset: enabled)
       Active: inactive (dead) since Sun 2020-11-15 14:25:19 GMT; 6min ago
      Process: 2317 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
     Main PID: 2317 (code=exited, status=0/SUCCESS)
    Nov 15 14:23:19 systemd[1]: Starting Postfix Mail Transport Agent...
    Nov 15 14:23:19 systemd[1]: Started Postfix Mail Transport Agent.
    Nov 15 14:25:19 systemd[1]: Stopped Postfix Mail Transport Agent.

    Service goes “inactive dead”

    Never takes longer than 2 minutes to terminate.

    The only hint i have is:

    Nov 15 14:25:19 altair postfix/postfix-script[2652]: stopping the Postfix mail system
    Nov 15 14:25:19 altair postfix/master[2311]: terminating on signal 15

    Is empty

    I tried reinstalling, reconfiguring but problem stays.

    However…. I have a second server (different ip) with exactly same configuration and it works perfect.

    The only difference is that the domain on this server is coming from another package.
    I set the DNS MX Record on high priority to

    I dont think its a DNS problem.

    Any suggestions for me?

    Thank you very much

    • Xiao Guoan (Admin)
      3 years ago

      You can open the /var/log/syslog file to see if you can find any clue. Search for the word “kill” in this file.

      For example,

      systemd invoked oom-killer: gfp_mask=0x14200ca(GFP_HIGHUSER_MOVABLE), nodemask=(null), order=0, oom_score_adj=0
      Out of memory: Kill process 18211 (mysqld) score 245 or sacrifice child

      This indicates the server ran out of memory, so it killed the mysqld process.

      • Geronimo Stade
        3 years ago

        Yeh. I thought so, i am not too unexperienced actually but this one got me… I had the hope you might have seen this or similar issue before.

        Let me just setup everything new including reinstall of OS to ensure there is not a totally bad misconfig somewhere.
        If still not working i will inform you and maybe you might want to take a look at it. If you find the time of course., ssh would not be an issue.

        Thank you for your absolutely great Tutoarials! To me this is like “cheat sheets”, well chosen information, good explaination.

        Have a great week!


        • Geronimo Stade
          3 years ago

          Doh! It was so easy…

          Good old pkill did the trick. Even the log (verbosly) didnt say anything and even after restart the process got started and then seem to block the ports required.

          Solution was:

          # sudo systemctl disable dovecot
          # sudo systemctl disable postfix

          # rm /var/spool/postfix/pid/

          # pkill [master pid]

          sudo reboot now
          # sudo systemctl enable postfix
          # sudo systemctl enable dovecot

          Thank you!!!!

        • IMRON HS
          3 years ago

          Thank you, work for me!

  • Trevor
    3 years ago

    Hi, I am (kind of) new to self-hosting mail servers. I have followed your directions except in that I have SSL certificates with AlphaSSL. I have several files and I’m not sure how to make them all work with the system. I was wondering if you or anyone here might be able to help guide me in the right direction. I also have an issue where postfix just stops. I can’t seem to find out why. Might be related to the certificates issue. I had it partially working (could send/receive mail from an external mail client on a different machine while postfix was active) and in diagnosing the certificate issue I seem to have broken it to the point where I’m not receiving or sending any mail any longer.

    • Xiao Guoan (Admin)
      3 years ago

      I don’t see any advantage in using a paid SSL certificate on mail servers. Just use free Let’s Encrypt certificate with certbot, which can automate certificate renewal.

  • Steve
    3 years ago

    Thank you very much for this. After years away from looking after mail servers I need to set one up for a customer and this is exactly what I need.

    Assuming it all works of course 🙂

  • Forma
    3 years ago

    I have a question I get this message when trying to send an email from my webserver to gmail:

    Nov 24 10:55:06 mail postfix/pickup[361926]: E899E2AA052C: uid=1000 from=
    Nov 24 10:55:06 mail postfix/cleanup[366518]: E899E2AA052C: message-id=
    Nov 24 10:55:07 mail postfix/qmgr[361927]: E899E2AA052C: from=, size=382, nrcpt=1 (queue active)
    Nov 24 10:55:08 mail postfix/smtp[366520]: E899E2AA052C: to=,[]:25, delay=1.5, delays=0.2/0.02/1/0.31, dsn=5.7.1, status=bounced (host[] said: 550-5.7.1 [] The IP you're using to send mail is not authorized to 550-5.7.1 send email directly to our servers. Please use the SMTP relay at your 550-5.7.1 service provider instead. Learn more at 550 5.7.1 u24si1950242wmc.105 - gsmtp (in reply to end of DATA command))

    Is this error message regarding the PTR record that is not setup on my ip address to my domain?

    Thank you.

    • Xiao Guoan (Admin)
      3 years ago

      This means your IP address has been blacklisted by Gmail. It’s not recommended to use a residential IP address with your mail server. Residential IP addresses have poor reputation.

      • Forma
        3 years ago

        sorry this is not a residential ip address, it is a business static ip address from my ISP.
        Is there any way to get it out of the blacklist?

        That is strange.

    • Xiao Guoan (Admin)
      3 years ago

      You have several options:

      1.) Ask Gmail to remove your IP address from blacklist.
      2.) Ask your ISP to change your IP address.
      3.) Set up SMTP relay to bypass blacklisting.
      4.) Host your mail server in a data center like Kamatera
      5.) Host the main mail server on-premises and use your own send-only SMTP server hosted in a data center to send emails.

  • Tony Dee
    3 years ago

    Great tutorial.

    To create a new user ‘most’ for an adduser command can be used. But how about if you want to create a new user ‘most.wanted’ for Adduser command will return an error. There is a method for creating virtual users using MySQL, but I do not want to use database. Also creating alias ‘most.wanted: most’ in /etc/aliases will only forward emails from most.wanted to most.

  • Liviu Damian
    3 years ago

    Excellent tutorial.

  • Michael
    3 years ago

    First of all awesome article series…I love reading your articles. I am trying to read Part 11 How to Secure Email Server Against Hacking with Self-hosted VPN Server but it comes back with 404 Page not found. Would you be able to re-post that article?

    • Xiao Guoan (Admin)
      3 years ago

      Thanks for letting me know. The 404 not found problem was caused by a malfunctioning page cache. Now you should be able to read part 11.

  • sokha
    3 years ago

    i’m not clear how to create email alias

    • Xiao Guoan (Admin)
      3 years ago

      Here’s an example /etc/aliases file.

      • sokha
        3 years ago

        thank you sir for your reply but i still stuck when i try to install certificate
        sudo certbot certonly -a nginx –agree-tos –no-eff-email –staple-ocsp –email [email protected] -d i get output
        Saving debug log to /var/log/letsencrypt/letsencrypt.log
        Plugins selected: Authenticator nginx, Installer None
        Obtaining a new certificate
        Performing the following challenges:
        http-01 challenge for
        Waiting for verification…
        Challenge failed for domain
        http-01 challenge for
        Cleaning up challenges
        Some challenges have failed.

        – The following errors were reported by the server:

        Type: unauthorized
        Detail: Invalid response from
        []: “\r\n\r\n\r\n
        i have some error
        dovecot.service – Dovecot IMAP/POP3 email server
        Loaded: loaded (/lib/systemd/system/dovecot.service; enabled; vendo>
        Active: failed (Result: exit-code) since Sun 2021-01-17 20:54:13 PS>
        Docs: man:dovecot(1)
        Process: 5234 ExecStart=/usr/sbin/dovecot -F (code=exited, status=89)
        Main PID: 5234 (code=exited, status=89)

        Jan 17 20:54:13 systemd[1]: Started Dovecot IMAP/P>
        Jan 17 20:54:13 dovecot[5234]: doveconf: Fatal: Er>
        Jan 17 20:54:13 systemd[1]: dovecot.service: Main >
        Jan 17 20:54:13 systemd[1]: dovecot.service: Faile>

  • so when i tried to send mail by execute “echo “test mail” | sendmail [email protected]”, i got a “502 5.5.1 Unrecognized command. w14si12955002pgi.428 – gsmtp” error, after successful telnet to 25, any possible causes?

    • i could found “sendmail” binary in /usr/sbin

  • sorry, my bad. i was trying to execute this command in telnet XD
    please delete this message, thank you

  • chris
    3 years ago

    thanks for your great tutorials.

  • David Collantes
    3 years ago

    @Xiao Guoan, what kind of VM (VPS) do you recommend which will handle your email series setup, all the way up to part 8? I am trying to figure out if a Vultr’s $5/month (1 CPU, 1024MB RAM) would do.

    • Xiao Guoan (Admin)
      3 years ago

      Yes. 1GB RAM is enough up to part 8. When you add SpamAssassin+ClamAV+Amavis to your setup, you need at least 3GB RAM.

  • @Xiao Guoan,

    Thank you for this tutorial. I’m at the state where “echo “test email” | sendmail [email protected]” results in a bounce-back with the following message from mail.log:

     Apr 24 09:42:22 user postfix/pickup[25941]: B435E60017E: uid=1000 from=
    Apr 24 09:42:22 user postfix/cleanup[30965]: B435E60017E: message-id=
    Apr 24 09:42:22 user postfix/qmgr[25942]: B435E60017E: from=, size=391, nrcpt=1 (queue active)
    Apr 24 09:42:22 user postfix/smtpd[30968]: connect from localhost[]
    Apr 24 09:42:22 user postfix/smtp[30967]: warning: host[]:25 greeted me with my own hostname
    Apr 24 09:42:22 users postfix/smtp[30967]: warning: host[]:25 replied to HELO/EHLO with my own hostname
    Apr 24 09:42:23 user postfix/smtp[30967]: B435E60017E: to=,[]:25, delay=0.27, delays=0.03/0.01/0.23/0, dsn=5.4.6, status=bounced (mail for loops back to myself) 

    I’ve looked around for people having similar situations and answers are all over the place. Is this a DNS issue on my end? Running Linux Mint 19.2 as a server in my house. I have my own FQDN with Dynamic DNS. Can send emails to the house from Gmail.


    • Xiao Guoan (Admin)
      3 years ago

      Have you followed Postfix tutorial from other websites? I recommended purging your current Postfix configurations with the following command.

      sudo apt purge postfix

      So you can start with a clean slate.

  • Peter Kim
    3 years ago

    Hi Xiao,
    Thanks for the great post!
    I was following along great, then faced a problem when trying to receive mails..
    I can now send mails no problem, but when I try to send mails to my mail server, the it fails with following message.

    A message that you sent could not be delivered to one or more of its
    recipients. This is a permanent error. The following address(es) failed:

    [email protected]
    all relevant MX records point to non-existent hosts
    Reporting-MTA: dns;

    Action: failed
    Final-Recipient: rfc822;[email protected]
    Status: 5.0.0

    I think my DNS is failing and not sure where it went wrong.

    A record ip-address
    Mx Record @

    If you could please help, it would be much appreciated 🙂

    • Peter Kim
      3 years ago

      * Fixed
      My server was actually already hosting a webserver and that may be the reason why I had to set my domain settings differently.

      Below setting worked for me

      A record
      Host:mail Value: iptomyserver

      MXE record instead of MX

      Value: iptomyserver

Comments are closed. For paid support, please contact [email protected]