Managed Kubernetes now available in Open Beta. Test out the new service yourself at your Control Panel.

Updated on 17.5.2022

How to secure Postfix using Let’s Encrypt

Let's Encrypt Postfix and Dovecot

If you have registered a domain name and would like to use it for email, you might want to set up a mail transfer agent (MTA) through which you can send and receive messages. A great option for an MTA software is the free and open-source Postfix that aims to be fast, easy to administer, and secure. Ensuring a secure Postfix server in any network requires great care in its configuration, but with the help of Let’s Encrypt and Dovecot, the whole process is practically plug-n-play.

Try UpCloud for free! Deploy a server in just 45 seconds

This guide goes through the steps required in configuring a secure Postfix STMP server with certificates provided by the Let’s Encrypt certificate authority and Dovecot that is used for client authentication. The instructions listed below are intended for Ubuntu 16.04, but the components are available on other distributions as well with just minor changes to the installation command.

Let's Encrypt Postfix and Dovecot

Creating DNS records

The first step in setting up a trustworthy email server is to create the required domain name and mail exchanger records. This process will differ depending on which Domain Name Server you are using to manage your domain name. Most domain name servers will provide instructions or documentation on how these settings can be done.

For example, you could add a subdomain for your SMTP server such as and enable an MX record that points to that subdomain.

The records that you will need to configure:

  • DNS A record, that maps your domain name to the server’s public IP address.   A
  • MX record, which will tell other mail servers where messages send to your domain should be delivered.   MX   1
    @             MX   2
  • Reverse DNS record, that allows servers to check what domain your server’s IP address belongs to.
    Editing the PTR record

You can set the reverse DNS name per public IP address at your UpCloud control panel under Server settings and IP Addresses tab.

These settings might take a moment to propagate to other DNS servers so it is good to get them done early.

Installing Postfix

Postfix is the default MTA for Ubuntu and can be installed directly with the package manager. Use the following command to install the required packages.

sudo apt install postfix

Once the installation is complete, the setup will run a configuration script that asks to define a few settings, select the defaults for now by pressing enter to continue.

With Postfix installed, run the full configuration script to define the settings as below.

sudo dpkg-reconfigure postfix

The reconfiguration command will display the configuration interface again, select the following values in order of appearance.

  1. General type of mail configuration:
    Internet Site
  2. System mail name – Replace the <> with your domain name:
  3. Root and postmaster mail recipient – Any Unix user account:
  4. Other destinations to accept mail for – Include $mydomain as the final destination:
    $mydomain, $myhostname, localhost.$myhostname, , localhost
  5. Force synchronous updates on mail queue?
  6. Local networks: [::ffff:]/104 [::1]/128
  7. Mailbox size limit (bytes):
  8. Local address extension character:
  9. Internet protocols to use:

The configuration is written into the /etc/postfix/ file. In case you want to make changes to the above settings, you can always run the reconfiguration script again.

By default, Postfix uses the mbox mailbox format. Another commonly used option is Maildir which stores emails in individual files reducing the chance of your mail database getting corrupted. The following settings will use Maildir but you are free to choose any format. If you wish to use something else, remember to also configure it for Dovecot.

Rather than editing the configuration file directly, you can use the postconf -e command to change the Postfix parameters.

sudo postconf -e 'home_mailbox = Maildir/'

Using the Maildir mailbox format emails are stored in under the recipient user’s home folder /home/<username>/Maildir.

Also, tell Postfix what domain it is the final destination for so that it can be easily referenced as a Postfix variable as was already shown in the configuration script.

sudo postconf -e 'mydomain = <>'

Now that Postfix is installed, you can continue below with further configurations.

Getting Let’s Encrypt certificates

Enabling the TLS will require you to obtain certificates. Let’s Encrypt is a free, automated, and open Certificate Authority that allows easy certificate setup using the Certbot ACME client from the Electronic Frontier Foundation.

An easy way to get the certificates issued on a server that does not have a running web server is to use the client with the --standalone plug-in. Start by installing the Let’s Encrypt module.

sudo apt install certbot

Once the install is finished, you can run the process with the easy command below. Replace the with your domain name.

sudo certbot certonly --standalone -d

The command starts an interactive configuration script which will ask a couple of questions to set up the certificate correctly.

  1. Select Yes to use the default vhost file and specify the settings manually.
  2. Enter the email server’s domain name like
  3. On the first installation on any specific host, you’ll need to enter a contact email.
  4. Read the Let’s Encrypt Terms of Service and select Agree to continue.
  5. Then select whether you wish to use both HTTP and HTTPS or to require all traffic to use encryption by highlighting either the Easy or the Secure option and selecting OK.

If everything worked correctly you’ll get a message that HTTPS was successfully enabled.

If you already have a web service installed on your mail server, you can find more about how to obtain certificates with Apache2 or Nginx in their software-specific instructions.

Once you have finished the process, the certificates will be stored under /etc/letsencrypt/live/<your.domain>/. You can add your new certificates to the Postfix configuration using the two commands below. Replace the <your.domain> with your email server’s domain name.

sudo postconf -e 'smtpd_tls_cert_file = /etc/letsencrypt/live/<your.domain>/fullchain.pem'
sudo postconf -e 'smtpd_tls_key_file = /etc/letsencrypt/live/<your.domain>/privkey.pem'

With the certificate installed, you can configure the rest of the email server.

Setting up SMTP authentication

Next, you should enable SMTP-AUTH, which allows a client to identify itself through the authentication mechanism SASL. Transport Layer Security (TLS) should be used to encrypt the authentication process. Once authenticated, the server will allow the client to relay mail.

Enter the following edits as they are.

sudo postconf -e 'smtpd_sasl_type = dovecot'
sudo postconf -e 'smtpd_sasl_path = private/auth'
sudo postconf -e 'smtpd_sasl_local_domain ='
sudo postconf -e 'smtpd_sasl_security_options = noanonymous'
sudo postconf -e 'broken_sasl_auth_clients = yes'
sudo postconf -e 'smtpd_sasl_auth_enable = yes'
sudo postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination'

Then configure Postfix to provide TLS encryption for both incoming and outgoing mail.

sudo postconf -e 'smtp_tls_security_level = may'
sudo postconf -e 'smtpd_tls_security_level = may'
sudo postconf -e 'smtp_tls_note_starttls_offer = yes'
sudo postconf -e 'smtpd_tls_loglevel = 1'
sudo postconf -e 'smtpd_tls_received_header = yes'

Enabling the SASL lets users send messaged outside the local domain without compromising the security of the relay.

Virtual alias mapping

The last bit of configurations for Postfix is to map the email addresses you wish to use to your user accounts. With virtual alias domains, each hosted address can be aliased to a local UNIX system account or a remote address. Enable virtual alias mapping with the following two edit commands.

sudo postconf -e 'virtual_alias_domains = $mydomain'
sudo postconf -e 'virtual_alias_maps = hash:/etc/postfix/virtual'

You can then create the alias map indicated above. The example below shows how to use this mechanism for the domain. Assign the email addresses you want to enable to a username using the same pattern of <[email protected]> <username>.

sudo nano /etc/postfix/virtual
[email protected] root
[email protected] root
[email protected] info

Once you have configured the virtual aliases, tell Postfix to generate the required database file from the list.

sudo postmap /etc/postfix/virtual

Then restart Postfix itself to apply the full configuration.

sudo systemctl restart postfix

You might also want to add the Maildir setup to the user home directory template so that it is automatically configured when a new user account is created.

sudo maildirmake.dovecot /etc/skel/Maildir
sudo maildirmake.dovecot /etc/skel/Maildir/.Drafts
sudo maildirmake.dovecot /etc/skel/Maildir/.Sent
sudo maildirmake.dovecot /etc/skel/Maildir/.Trash
sudo maildirmake.dovecot /etc/skel/Maildir/.Templates

The same Maildir can be added to the current user with the commands below. Replace the $USER with any existing username if that user does not have sudo privileges.

sudo cp -r /etc/skel/Maildir /home/$USER/
sudo chown -R $USER:$USER /home/$USER/Maildir
sudo chmod -R 700 /home/$USER/Maildir
sudo adduser $USER mail

Finally, include the Maildir location in your terminal and mail profiles.

echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/

Relog to the terminal to apply the group changes by reopening the SSH connection.

Configuring Dovecot

Postfix supports two SASL implementations, that are used for authentication, Cyrus and Dovecot. Of these two, Dovecot is relatively simple to configure and was therefore selected for this guide. To enable Dovecot SASL you will need to install the dovecot-common package. You might also wish to install the Dovecot plugins for IMAP and POP3 to allow connections from mail clients such as Thunderbird or Outlook.

sudo apt install dovecot-common dovecot-imapd dovecot-pop3d

Once installed, you will need to make some changes to a few of the configuration files. Dovecot configuration is split between a number of files under /etc/dovecot/conf.d/. To enable the required security features, make the changes and indicated below to the next four .conf files.

Start by disabling the plaintext authentication at the top and enabling login authentication mechanism near the end of the auth.conf file.

sudo nano /etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = yes
auth_mechanisms = plain login

Then instruct the mail directory to use the same format as Postfix.

sudo nano /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:~/Maildir

Next, configure the IMAP and POP3 protocols for email clients in the master.conf file as shown below. Uncomment the port lines shown underneath by deleting ‘#’ sign at the start of these lines. In the same file, also edit the service auth segment to allow user authentication.

sudo nano /etc/dovecot/conf.d/10-master.conf
service imap-login {
   inet_listener imap {
      port = 143
service pop3-login {
   inet_listener pop3 {
      port = 110
service auth {
   # Postfix smtp-auth
   unix_listener /var/spool/postfix/private/auth {
      mode = 0660
      user = postfix
      group = postfix

Most email clients default to the standard ports, 143 for IMAP and 110 for POP3. With STARTTLS required for every connection, there is no need to duplicate the services to the SSL dedicated ports.

You will also need to include your certificates in the Dovecot ssl.conf file, replace the <> with your server’s domain name. Select to require SSL and also disable the insecure SSLv2 and SSLv3 protocols.

sudo nano /etc/dovecot/conf.d/10-ssl.conf
# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = required
ssl_cert = </etc/letsencrypt/live/<>/fullchain.pem
ssl_key = </etc/letsencrypt/live/<>/privkey.pem
# SSL protocols to use
ssl_protocols = !SSLv2 !SSLv3

When you are done editing the files, you can check the Dovecot configuration with the following command.

dovecot -n

Once everything looks correct, restart Dovecot to apply the new settings.

sudo systemctl restart dovecot

That is it! Congratulations, your mail server is now ready to receive and send emails using secure authentication.

Testing the SMTP server locally

You can test the Postfix server locally from the terminal by using a direct connection with netcat, telnet or similar. The following commands need to be executed in the correct order or the server will close the connection.

nc 25
EHLO $hostname
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
Subject: Test email

Body of the email

If the configuration worked correctly, you should see a confirmation that the email you just wrote has been placed in the queue and will arrive momentarily.

Note that using this method you can only send emails to your own domain addresses. When attempting to set recipient outside your own domain, you will see a message stating that relay access is denied and the connection will be closed.

Another little more convenient way to use email from the terminal is to install Mailutils.

sudo apt install mailutils

It can be used to check mail with the simple command below.


You can also test sending mail using the same utility by adding the recipient address.

mail [email protected]

Then complete the email form with subject and body text. Send the message by pressing Ctrl+D which exits the utility. Using this method will allow you to send messages outside your network. However, the sender and return addresses will show your username and server domain name, e.g. [email protected], instead of the probably more desirable [email protected] Therefore this method should only be used for testing purposes.

Additional security options

The main concerns of running a private SMTP server will be combating both incoming and outgoing spam messages. A secure configuration and strong user passwords will help with the latter but you might wish to take additional steps to prevent incoming spam.

Reject bad connections and spam messages

Tightening the rules for SMTP connections can stop many of the common spambots that disregard email etiquette. Requiring a valid HELO or EHLO command with a fully qualified domain name can do just that. Add the following parameters to further improve your secure Postfix configuration.

sudo postconf -e 'smtpd_helo_required = yes'
sudo postconf -e 'smtpd_helo_restrictions = reject_non_fqdn_helo_hostname,reject_invalid_helo_hostname,reject_unknown_helo_hostname'

Postfix supports a verify (VRFY) command which allows anyone to determine if an account exists on the system, which can provide significant assistance to any brute force attack on your user accounts. VRFY may also give out sensitive information about the users, such as the account owners full name. It is recommended to disable the VRFY command with the following parameter.

sudo postconf -e 'disable_vrfy_command = yes'

You might also wish to delay the reject message to allow Postfix to log recipient address information when the connected client breaks any of the reject rules. This allows you to later find out who the spammers were trying to target.

sudo postconf -e 'smtpd_delay_reject = yes'

The Postfix recipient restrictions that were set in the SASL configuration part are important in securing the server while allowing users to connect with email clients such as Thunderbird or Outlook. Keeping these parameters in the right order will retain this ability, but you can include further restrictions that incoming messages will need to comply with.

sudo postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination,reject_invalid_hostname,reject_non_fqdn_hostname,reject_non_fqdn_sender,reject_non_fqdn_recipient,reject_unknown_sender_domain,reject_rbl_client,reject_rbl_client'

The parameters above are fairly self-explanatory though a little difficult to read in a terminal copy paste friendly format. The general idea is to reject connections from made up addresses that do not use a fully qualified domain name or simply do not exist. Here is possible to also add external spam filters such as the Spamhaus or CBL blacklists. If you wish to find out more, Postfix has a very extensive documentation on its configuration options.

Directing spam to /dev/null

Postfix supports a so-called catch-all address with the virtual aliases. Any emails sent to an address not specified in the virtual map will be directed according to the catch-all address. This is useful to hide the valid addresses by allowing mail delivery to any address hence preventing spammers from finding real users through simple trial and error.

Enable the catch-all address by adding a line as shown in the example below to the end of your virtual mapping without any local part and direct the messages to a virtual user nobody.

sudo nano /etc/postfix/virtual
... nobody

To prevent spam from filling up all of your storage space, edit the system aliases list to direct messages sent to invalid addresses straight to /dev/null.

sudo nano /etc/aliases
# See man 5 aliases for format
postmaster: root
nobody: /dev/null

Once you have configured both the system and virtual aliases, tell Postfix to regenerate the required database files from these lists.

sudo postmap /etc/postfix/virtual
sudo postalias /etc/aliases

Then reload Postfix again to enable the new settings.

sudo service postfix reload

You can test the spam trap by sending a message to any random unconfigured email address, the mail should be delivered successfully but will not be stored. Another way to test this is by using an address validator such as the Email Checker, any address should show up as valid, even the none existing ones.

Maintaining security

Configuring and maintaining a secure Postfix SMTP server only requires a basic understanding of the components, but simple mistakes in the setup can render the security settings ineffective, therefore most important part is to make sure the server does not become an open relay. Conveniently MX Toolbox, an online network testing utility, provides an SMTP diagnostics tool with which you can easily test your configuration by just entering your mail server domain name such as With the setup used in this guide, everything should show green in their tests, granted that the DNS rules have propagated.

While a configuration helps to keep your SMTP server secure, strong user passwords are also very important. In such a case that a third party was to gain unauthorised access to one of the user account, they would be able to send spam messages unhindered using your infrastructure and tarnish your network reputation. A common way to reduce the chance of someone guessing your user’s passwords is to impose limitations to failed logging attempts with Fail2ban. You can read more about install Fail2ban on Ubuntu in its own article to further improve the server security.

General good usage practices can also bring your server security a long way. In addition to the aforementioned security methods, Linux systems offer documentation ways to minimise vulnerabilities and harden your cloud server against abuse. Take a look at our introductory guide on how to secure your Linux cloud server if you wish to learn more.

Janne Ruostemaa

  1. Excellent article, Janne.

    Just a few nits…

    Now, !SSLv2 (only !SSLv3) should not be included in /etc/dovecot/conf.d/10-ssl.conf

    Also, I seem to recall an error occurring when adding the user before configuring dovecot.

    Another thing to be aware of is verifying that a PTR record exists. You can check for that here:

    Thank you for sharing!


  2. Ashu Tikekar

    I need some help with my Postfix installation. I am having problems when remote clients try to connect. They are able to connect to IMAP 993 with no issues. The problem is happening with SMTP.

    Will you be able to help ?

  3. Thank you for a very good guide.

    However, att least in Ubuntu 16.04, port 587 is disabled by default. Therefore, in /etc/postfix/ I hade to uncomment #submission inet n – n – – smtpd.
    Before that “unix_listener /var/spool/postfix/private/auth” did not work.

    I spent several hours before I got everything to work.

    I think you should update your guide.

    Best Regards


  4. Great tut, Janne! ??
    Q: is there a way to use different certificates for SMTP when the server is hosting multiple domains (=virtual hosts)?
    I host and on server Both domains have sep. hosts w. individual certs.
    I’d like user of Domain use the cert, the owner of use the cert for outgoing mail/SMTP. Is this possible or do both and have to use the cert for SMTP? :)

  5. Error with this line
    -su: syntax error

    sudo letsencrypt certonly –standalone -d

  6. Hi Janne, thank you for your great tutorial. I have a question, after following your steps to configure the postfix, It’s successful to sent email, but I have problem when send email from other machine, seems only work internally. Do you know if there’s configuration I need to set up in order to do that? thanks!

    example: from postfix server sent to my gmail is fine, but using python script to send email from other PC is failed.

  7. Hi janne,

    Thank you very much for your tutorial. Sending mails work very good for me, but i cant receive. Also every time after reset mail service everything is back again and i have to do whole process again

  8. Tamko Clarence

    Hi. please what mail client can i use in this case. can roundcube work?

  9. When using standalone, do you need an Apache virtual host set up for the mail.example.tld domain for it to work? I’ve only ever use LE with actual web sites, so just wondered before I get started if I need to do that first.

  10. Great tutorial, works like a charm on Centos 7 with just some changes

  11. Thank you so much for spending the time to do such a detailed tutorial. Fantastic. Really easy to follow.

    The only issue I encountered was that the latest dovcot has replaced the ssl_protocols setting with ssl_min_protocol.

  12. do i missed dovecot installation step?
    i couldn’t find it here

  13. Hi! Great tutorial!

    Just wanted to point out that the ‘sudo maildirmake.dovecot’ commands are shown *before* dovecot is actually installed. The dovecot installation line is a bit below the ‘sudo maildirmake.dovecot’ commands.

    Someone else pointed this out, but it really is out of order.

    Thanks! :-)

  14. Hello very good tutorial, but I want to ask why the imap port does not work, the smtp with port 587 works perfect but the imap 143 does not work, RainLoop says
    MailSo-Net-Exceptions-SocketReadTimeoutException (NetClient.php ~ 514),
    I appreciate if you have any idea what may be happening and how it can be solved, thanks

  15. Hi, thanks for the great tutorial. I was able to set up the server and emails are working as expected with Squirrel mail. However, If I try to connect to Thunderbird I’m not able to send emails, I can receive though.
    I checked that thunderbird uses default outgoing port 465 and In my server, there’s nothing running on port 465. I tried to enable smtps in /etc/postfix/ but I’m still not able to connect. I also verified the settings of postfix and dovecot twice from this tutorial.
    Please let me know if I’m missing something.
    Thank you.

    1. Yep same problem. Either the tutorial is incomplete or port 465 just wasn’t configured. Pity because 465 is now the “norm” apart from 587.

      1. Janne Ruostemaa

        Hi Eugene, thanks for the comment. 587 is still the default port for email submission. IANA has reassigned 465 to a new service and it should no longer be used for SMTP communications.

  16. Bobby Zandavi

    Thanks for your helpful guide.

    I noticed a small error you might want to fix:

    “dovecot -n” should be “doveconf -n”

  17. Hello, thank you so much for professional tips, it helps me setup on Debian 8.

  18. Jonas Lindström

    Very good guide. I run Centos 8 but was able to set up a mail server by following your guide, with a few minor tweaks. No dpkg-reconfigure of course, and I could not find maildirmake. Had some problems getting certbot –standalone to work, but since I had Apache running certbot –apache did the trick. In all, very helpful. I especially appreciate the section about security.

  19. Hi. First thanks for your article. It’s really useful.

    But there’s something that I don’t understand and could find anything that explains clearly. We are setting smtp authentication. It’s ok. But how we will authenticate, what identity we should use for this.

    If you can clear this point, I’ll be appricated.

    Thank you.

  20. Run very well in Debian 10. Thanks.

  21. Hello Janne, I followed this tutorial very carefully on Ubuntu Server 18.04 but I am only able to get it to work for internal emails. Emails to gmail and other email service providers bounced back.

    I tested the email server on and it returned three errors: ‘Reverse DNS does not match SMTP banner’, ‘Does not support TLS’ and ‘Maybe an open relay’. Ports 110 and 25 are open but I still cannot download or send emails with Thunderbird or Outlook. I have also tried with SMTP port 587 and uncomment the ‘smtpd submission’ line in the /etc/postfix/ but it still does not work. Firewall is allowing Postfix, Dovecot POP3 and 25/tcp.

    Hitting a wall here, so I hope you can help. Thank you.

  22. Very wonderful tutorial. It is very easy to follow. Please help me, after I completed setting postfix, dovecot configuration failed. Tried to fix. But now I can send or receive any email. The msg smtp connection failed shows up.
    What did I miss.

  23. Hello

    I’ve created a wildcard certificate using certbot and I’m wondering if there can be any conflict with any clients or servers where it only accepts non-windcard certificates?

    mxtoolbox and reports no problems with my server (except that with, I can’t get mandetoryTLS to work and according to it shouldnt be, to satisfy RFC 3207).
    Anyways, my only problem is that only Outlook Android does not want to accept the certificate, and when it doesnt show a certificate error message when adding the account, it will just simply not load the account, and according to the enabled verbose dovecot logs, it does not connect to the server at all.

  24. Thank you very much for this excellent tutorial. After 48 hours (!) of failing by following other tutorials online and trying to modify the openssl parts, I finally found your tutorial. I had Let’s Encrypt certificates already that I wanted to use thanks to the auto renewal service. Not only was your tutorial the easiest to follow, it was the quickest to implement and the first one that fully worked! Really appreciated. Tested first on PiOS (Debian Buster). I made a couple of mistakes, but the answers were all in the tutorial.

    Hints for others: remember to open ports on your router and servers firewalls (ufw or similar), read above about opening port 587 (necessary for me when using AppleMail on MacOS) and . Also, read carefully about alias mapping: You need to map every single user, none get assigned an e-mail address automatically, including yourself. Finally, as mentioned above, don’t use ssl_protocols as described but instead ssl_min_protocol = TLSv1.2 for example. Thanks again!!

  25. Hi Guys great tutorial. I only have 1 issue. When i enable smtpd_sasl_auth_enable = yes’
    the server will stop accepting all connections.
    If i disable it, the server will send a receive mail fine, but i cannot connect any mail clients to it.

    I have followed everything in the guide.
    Ubuntu 20.
    I can submit logs if needed.
    Any help would be appreciated.

  26. I am receiving this message in response to any mail I send from external emails:

    The mail system

    : maildir delivery failed: create maildir file
    /root/Maildir/tmp/1622644453.P755393.: Not a directory

    The only user I have is root. This directory /root/Maildir/tmp/ exists but I think it needs /home/ before the rest of address

  27. Thanks a lot for this. It is really helpful and working great!


  28. Your solution works perfectly :)


Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top