Relaying with SMTP authentication


Your mail server is almost ready for use. But one puzzle piece is missing. Your users can already fetch emails but they need to be able to send emails, too. Mail server know how to send an email to another mail server by looking up MX records. And the receiving mail server will happily accept any email that is destined for a valid recipient. Mail clients however are expected to send email to their mail server first which then forwards email to the internet. When Postfix receives an email from a user and forwards it to another server this is called relaying. Postfix acts as a relay.

So why do the mail client not work the same way? Couldn’t they also just look up the MX record and send the email to the destination server? Technically, yes. But users are often sitting at home using a DSL line. And such IP networks are usually blocked off from sending mail. Some ISPs block the SMTP port on their routers. And most receiving mail servers check real-time blacklists to block DSL IP addresses. The reason is that home users are more likely to have infected Wind*ws PCs that send out spam.

Am I going too fast? Okay, let’s walk through the different scenarios one by one.

Incoming email

When someone on the internet sends an email to, some other mail server will deliver the email using SMTP to your mail server. Postfix will determine that it’s responsible for email addresses in the domain and accept the email. John can then use POP3 or IMAP to fetch the email from your server.

Outgoing email (without authentication)

John is on the internet somewhere and wants to send an email to Your mail server is not responsible for the “” domain so it receives John’s email and would have to forward (relay) it to the mail server that is responsible for … email addresses. This may seem like a harmless scenario but your mail server must deny that:

Why? Because anyone can claim to be John and make your mail server forward mail. If an attacker (like a spammer) would send millions of spam emails in John’s name through your server then other organisations will accuse you as the operator of the mail server of spamming. Your mail server would be what people call an open relay. This is not what you want because your mail server would get blacklisted and you will not be able to send out mail to most other servers. So without any proof that John is actually John your server must reject the email.

Outgoing email (with authentication)

So how does John prove his identity? He needs to use authenticated SMTP. This is similar to the previous case but John’s email program will also send his username and password.

Of course we are making sure that his authentication happens over an encrypted connection so John’s password is blared out.

Postfix setting “mynetworks”

In addition to using SMTP authentication you can tell Postfix to always relay email for certain IP addresses. The mynetworks setting contains the list of IP networks or IP addresses that you trust. Usually you define your own local network here. The reason John had to authenticate in the above example is because he is not sending the email from your local network.

If your users are using the webmail interface running on your mail server then they will not need to authenticate. Roundcube sends email to localhost which is trusted according to the mynetworks setting.

Make Postfix use Dovecot for authentication

Enabling SMTP authentication in Postfix is surprisingly easy. You already configured Dovecot’s regarding user authentication. So let’s just make Postfix utilize that by telling it to ask the Dovecot server to verify the username and password. Postfix just needs some extra configuration. Run these commands on the shell:

postconf smtpd_sasl_type=dovecot
postconf smtpd_sasl_path=private/auth
postconf smtpd_sasl_auth_enable=yes

This enables SMTP authentication and tells Postfix that it can talk to Dovecot through a socket file located at /var/spool/postfix/private/auth. Do you remember that Postfix runs in a sandboxed chroot directory? That’s at /var/spool/postfix. It cannot access any files outside of that directory. But fortunately in a previous section you edited the /etc/dovecot/conf.d/10-master.conf file and made Dovecot place a socket file into /var/spool/postfix/private/auth to allow communication from Postfix.

Enable encryption

The following settings enable encryption, define the key and certificate and enforce that authentication must only occur over encrypted connections:

postconf smtpd_tls_security_level=may
postconf smtpd_tls_auth_only=yes
postconf smtpd_tls_cert_file=/etc/letsencrypt/live/
postconf smtpd_tls_key_file=/etc/letsencrypt/live/

Note #1: In the past you may have configured your smtpd_recipient_restrictions to restrict relaying to authenticated users. Postfix nowadays has setting called “smtpd_relay_restrictions” that deals with relaying requests in the “RCPT TO” phase of the SMTP dialog. So essentially it works like the good old “smtpd_recipient_restrictions” but is checked first. smtpd_relay_restrictions has a reasonable default so authenticated relaying works automatically.

Note #2: Postfix 2.10 has changed the behavior of the smtpd_*_restrictions altogether. If a restriction makes Postfix reject an email it will wait until after the “RCPT TO” line. Read the Postfix documentation for a description of the reasons for that change.

The smtpd_tls_security_level is set to “may” to allow encrypted communication when Postfix receives an email. This not only applies to users sending emails but also remote mail servers that send email to you. It may sound tempting to change that to “encrypt” which would enforce encryption and reject any attempts to create an unencrypted SMTP connection. But unfortunately there are still mail servers in the world that can’t encrypt and would not be able to deliver email to you. So “may” is the proper setting.

Although emails may still get delivered unencrypted from other servers we should make sure that users don’t accidentally (or out of ignorance) send their passwords unencrypted over the internet. That’s what we enforce “smtpd_tls_auth_only=yes”. Now our users should be safe.

How SMTP authentication works

Are you curious how SMTP authentication looks on a protocol level? Let’s go through that. In previous versions of this guide we used “telnet” to connect to TCP port 25 and speak SMTP. But now we enforce encryption and can’t do SMTP authentication unencrypted. Let’s try the unencrypted part:

telnet localhost smtp

The server will let you in:

Connected to localhost.
Escape character is '^]'.
220 mail ESMTP Postfix (Debian/GNU)

Say hello:


Postfix will present a list of features that are available during the SMTP dialog:

250-SIZE 10240000
250 DSN

Let me briefly explain what these lines mean:

    This is a feature to speed up SMTP communication. Usually the remote system has to wait for a response to every command it sends. Pipelining allows the remote server to send bulks of commands without waiting for a response. Postfix will just store these commands and execute them one by one. If you told Postfix to forbid pipelining it would disconnect the remote server when it tries to send bulks of commands without waiting for the proper reply. It is mainly a feature against spamming programs that don’t behave.
  • SIZE 10240000
    The remote server is allowed to send emails up to 10 MB large. This has long been a common maximum size for emails. However nowadays 40 MB or even more are more common sizes because emails have grown larger.
  • VRFY
    Allows remote servers to verify a given name or email address. For example the remote server could send “VRFY john” and your server might respond “250 John Doe <>”. It can be used to verify that a certain recipient email address is deliverable
  • ETRN
    A command that a remote system can send to flush the Postfix queue of mails for a certain domain. It can be used if the remote system had technical problems and failed to receive email for a while. Then it could send an ETRN command to make your server start sending outstanding emails for that domain. It is rarely used.
    This tells the remote system that it might start switching from this unencrypted to an encrypted connection by sending the “STARTTLS” command. It will then start negotiating a TLS-encrypted connection. You could compare it to an HTTP connection that suddenly switches over to an encrypted HTTPS connection. The advantage is that you can start talking SMTP on TCP port 25 and don’t have to open up a second TCP port like 465 which is the “SSMTP” (secure SMTP) port and only accepts encrypted connections.
    This enables more three-digit return codes for various conditions. See the RFC2034 if you are curious.
    In ancient times SMTP only processed 7-bit characters. You couldn’t transfer special characters like “Ä” or “ß” without special encoding. 8BITMIME allows a transmission of emails using 8-bit characters. Still many emails are specially encoded using ISO8859-1 or UTF-8.
  • DSN
    It enables DSNs (delivery status notofications) that allows the sender to control the messages that Postfix creates when an email could not be delivered as intended

However one important line is missing here that would allow us to send our username and password:


We told Postfix to only allow authentication when the connection is encrypted. So we are not offered authentication over this plaintext connection.

Are you still connected? Okay, good. So we need an encrypted connection using TLS. You could enter STARTTLS:


And the server would reply:

220 2.0.0 Ready to start TLS

However now it’s getting complicated because you would have to speak TLS encryption which is not a language that humans speak. So let’s quit this using the “QUIT” command.

But we can use OpenSSL to help us with the decryption. Now run:

openssl s_client -connect localhost:25 -starttls smtp

You will see a lot of output. OpenSSL has connected to TCP port 25 and issued a STARTTLS command to switch to an encrypted connection. So whatever you type now will get encrypted. Enter:


And Postfix will send a list of capabilities that will look like this:

250-SIZE 10240000
250 DSN

And now that we are using an encrypted connection Postfix offers us to authenticate. So let us send the authentication string with a Base64-encoded password:

AUTH PLAIN am9obkBleGFtcGxlLm9yZwBqb2huQGV4YW1wbGUub3JnAHN1bW1lcnN1bg==

The server should accept that authentication:

235 2.7.0 Authentication successful

Excellent. You are logged in through SMTP. Disconnect from Postfix:



221 2.0.0 Bye

Authentication works. Well done.

Base64-encoded passwords

You may wonder how I got to the long cryptic string that apparently contained John’s email address and his password. It is just a Base64-encoded (not encrypted!) version of the string “<NULL-BYTE><NULL-BYTE>summersun”.

One way to create that string is using Perl:

perl -MMIME::Base64 -e \
'print encode_base64("john\\0john\\0summersun")';

The submission port (optional)

Although I have been talking about SMTP on port 25 to relay mails there is actually a better way: using the submission port on TCP port 587 (as described in RFC 4409). The idea is to use port 25 for transporting email (MTA) from server to server and port 587 for submitting (MSA) email from a user to a mail server. As many users still use SMTP by default you will likely have to run both ports.

Edit your /etc/postfix/ file and add a service for the submission port like this (mind the indentation from the second line on). Don’t use the suggested and commented-out submission service in the – just ignore it.

submission inet n - - - - smtpd
 -o syslog_name=postfix/submission
 -o smtpd_tls_security_level=encrypt
 -o smtpd_sasl_auth_enable=yes
 -o smtpd_sasl_type=dovecot
 -o smtpd_sasl_path=private/auth
 -o smtpd_sasl_security_options=noanonymous
 -o smtpd_sender_login_maps=mysql:/etc/postfix/
 -o smtpd_sender_restrictions=reject_sender_login_mismatch
 -o smtpd_sasl_local_domain=$myhostname
 -o smtpd_client_restrictions=permit_sasl_authenticated,reject
 -o smtpd_recipient_restrictions=reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_sasl_authenticated,reject

Basically this new service uses the “smtpd” daemon which is the piece of software that responds if you open an SMTP connection on TCP port 25. But it gets a few extra options set…

  • in the /var/log/mail.log mark the connections to the submission port as “postfix/submission/smtpd” (syslog)
  • enforce encryption on this port (security level)
  • enforce user authentication (sasl)
  • make sure that an authenticated user can only send emails in their own name (sender_login_maps)

Restart the Postfix server:

service postfix restart

Your users can now use the submission port to send email.

Protecting against forged sender addresses

Wait a minute. We can make sure that a user can only send emails using their own sender address? Cool. How does that work? Take a look at this line we just used above when we added the submission service:


The smtpd_sender_login_maps is a Postfix mapping with two columns:

  1. the email address the user wants to use as a sender address
  2. the username that was used when authenticating at the mail server

The reason I am just using the /etc/postfix/ mapping is that it fits perfectly here. That mapping maps the email address to itself if it exists. Confused? Look at the SQL query that the “email2email” mapping runs:

SELECT email FROM virtual_users WHERE email='%s'

So when a user wants to relay an email Postfix checks the virtual_users table looking for the sender address. Say that John wants to send out an email from his email address “”. Postfix will check the virtual_users table if there are any rows with an email field like that. It will find one and return the email field – which is just again the email address. Postfix expects to get back the username that was used to login. We are using the email address as a login username – so that mapping works. Only if John would try to send an email with a forged sender address then Postfix will see that it does not match his account and reject the email. Your mail.log would read something like:

NOQUEUE: reject: RCPT from[…]: 553 5.7.1 <forged@email.address>: Sender address rejected: not owned by user; from=<forged@email.address> to=<…>

It is your own decision whether you want to use the smtpd_sender_restrictions like that.

28 thoughts on “Relaying with SMTP authentication

  • 2018-01-22 at 17:24

    Doesn’t `smtpd_sender_login_maps` also require `mysql:/etc/postfix/` in case you want to send an e-mail from one of your aliases?

    • 2018-01-23 at 07:55

      That’s right. I haven’t had that case yet. My users usually use their main address and just have aliases pointing to it. Your suggestion totally makes sense. Have you tried that?

      • 2018-01-23 at 08:45

        Yes I did and it works fine in most cases:
        In all scenarios I will assume that is the mailbox/account.

        Expected results (using as identity):
        1) [OK] Alias: source ( to account (
        2) [NOK] Alias: source ( to account (
        3) [OK] Catch-All: source ( to account (
        4) [NOK] Catch-All: source ( to account (

        “Unexpected”/not-working result (using as identity):
        source ( to alias (
        source ( to account (

        The above scenario will fail because it’s 2 levels deep and will thus result in a falsy result. However that’s in my opinion an edge-case. For performance and simplicity I would recommend users to use 1 level-deep aliases anyway.

  • 2018-01-22 at 22:45

    Hi , till this page i been following all steps ,
    MX email handeled by priority 0
    A record xxxxxx
    A record same xxxxxx :80
    #1 roundcub able to send email gmail but wont receive a reply on it , even tried sending from gmail to it its out from gmail but never received ?
    #2 i tried to add an email using Thunderbird client i was able to imap normal pass ,smtp mail.domain:587 ,only with this combination everything else fail ,it will received emails as well never send with errtor “Sending of the message failed.
    The message could not be sent because connecting to Outgoing server (SMTP) failed. The server may be unavailable or is refusing SMTP connections. Please verify that your Outgoing server (SMTP) settings are correct and try again.”?

    • 2018-01-22 at 22:47

      sorry typo its the opposite :
      MX email handeled by priority 0

    • 2018-01-23 at 07:58

      #1 If you dare mention the actual real domain we might be able to check if it works and what error we get when we try to deliver email there.

      #2 Please try with port 143, STARTTLS and “password, normal” in Thunderbird. That should work.

  • 2018-01-22 at 23:10

    Hi Christoph,
    I have followed this section and have 2 questions/observations.
    1) only one of the certificates for one domain is defined here in smtpd_tls_cert_file and smtpd_tls_cert_key so it will be used for encrypting all the smpt traffic disregarding the domain it will go out from? Would it be possible to have this for each domain separately somehow ?

    2) It seem that with this config gmail always receives un-authenticated messages (and is complaining about that fact a lot – actually moving mail straight to spam). Not sure about the cause with my shallow knowledge of postfix.

    Any insight would be appreciated

    • 2018-01-23 at 08:03

      #1 As far as I know SMTP clients do not support SNI (server name indication) that allow them to tell which host name they want to talk to. It’s just important that you present a certificate. “smtpd_*” by the way means the receiving side of Postfix. Any configuration option with “smtpd_” means incoming connections and anything with “smtp_*” is for outgoing.

      #2 I believe that “unauthenticated” means that it’s not DKIM signed. Although DKIM signatures will help keep mail out of spam I wonder if that’s really the only reason. Could it be that your IP address is on an RBL (blacklist)? Have you verified that?

      Regarding DKIM: I’m working on the section about that and expect it to be online in 1-2 weeks. That may help with the “unauthenticated” issue.

      • 2018-01-25 at 22:17

        Hi Christoph,
        thanks for the reply. and clarification about #1

        as for the #2 the IP seems to be listed in one spamlist in sweden (?) but nowhere else. The only thing I can think of is that the domain was moved between countries and maybe in combination with DKIM google just doesn’t like that?
        Anyway thanks again and I am looking forward to the DKIM part.

  • 2018-01-23 at 17:06


    postconf smtpd_tls_cert_file=/etc/letsencrypt/live/
    postconf smtpd_tls_key_file=/etc/letsencrypt/live/

    (since across the guide, we’ve used “”)

    • 2018-01-23 at 18:51

      Right, thanks

  • 2018-01-23 at 21:14

    Hi Christoph,

    for me, the VRFY command only works with the full e-mail: VRFY – Maybe you can verify this?


  • 2018-01-26 at 04:07

    Note: If you have any special characters such as @ or ‘ or ! you must put \ in front of it to escape the character.

    (i was getting fails until i tried that)

  • 2018-01-27 at 04:32

    Thanks for the new guide!

    I am having trouble with STARTTLS on the 587/submission. I can send mail to the server on 25/smtp and STARTTLS works. But if I send mail via port 587, I am offered STARTTLS, but get a try again later message – 454 4.3.0 Try again later

    I did not install rspamd. I am using amavis and spamassassin.

    Any hints on how to get this to work? It is working on Jessie.

    root@mailtest:/etc/postfix# telnet 587
    Connected to
    Escape character is ‘^]’.
    220 ESMTP Postfix (Debian/GNU)
    250-SIZE 10240000
    250 SMTPUTF8
    454 4.3.0 Try again later

    • 2018-01-27 at 18:47

      Found it!

      submission inet n – – – – smtpd should be submission inet n – y – – smtpd

      postfix is running in a jail!

      Thanks again! These guides are great and make it easy to set up our own email servers.

      • 2018-01-27 at 19:15

        OK, last comment in this conversation with myself… maybe

        It seems that between Jessie and Stretch the default for chroot has changed from yes to no.

        From Stretch:
        # ==========================================================================
        # service type private unpriv chroot wakeup maxproc command + args
        # (yes) (yes) ***(no)*** (never) (100)
        # ==========================================================================

        So any services that are pulled forward from Jessie need to be adjusted accordingly.

  • 2018-01-30 at 18:38

    Thanks a lot for this guide, just brilliant 🙂

    I had no issues so far, ev. worked really great, but now I am not able to authenticate
    AUTH PLAIN Base64-encodedPassword
    535 5.7.8 Error: authentication failed:

    I am able to log on to Roundcube, but if I try it to authenticate here it doesn’t work.
    So far I made ev. according to the manual and every check I did was successful.

    Any idea what I maybe missed ?


    • 2018-01-31 at 08:09

      Tests with a client worked well over port 587, seems that I had issues with the Base64-encoded password.

      • 2018-01-31 at 16:16

        Try this:

        perl -MMIME::Base64 -e \
        ‘print encode_base64(“john\\0john\\0summersun”)’;

        I copied it from the jessie guide and if it works for me.

        • 2018-01-31 at 16:54

          Looks like I had a copy paste problem in my CMS. The perl example on the page works now.

        • 2018-01-31 at 17:16

          Just perfect, it worked like this 🙂
          Thanks a lot for your help 🙂

  • 2018-01-31 at 14:45

    Thanks for the new guide!!!

    I want to make sure that an authenticated user can only send emails in their own name, but I have a problem when implementing reject_sender_login_mismatch in the submission port.

    I test from 2 different email clients (Evolution and Thunderbird) and the behavior is not the same when changing the identity of the sender.

    The following happens with the Evolution client:

    – The mail is rejected correctly.
    (5.7.1 : Sender address rejected: not owned by user

    – In the postfix logs, appears in the from.
    (Jan 31 09:47:12 mail postfix / qmgr [19885]: 5E4B61C08EC: from = , size = 530, nrcpt = 1 (queue active))

    With the Thunderbird client the following happens:

    – The mail is not rejected.

    – In the postfix logs appears in the from.

    I found that the difference between the two is in how the headers are made up:

    Evoution: Return-Path: and From:
    Thunderbird: Return-Path: and From:

    ¿Any idea how to solve the problem?


    From roundcube solve it with the following configuration in /etc/roundcube/

    // Set identities access level:
    // 0 – many identities with possibility to edit all params
    // 1 – many identities with possibility to edit all params but not email address
    // 2 – one identity with possibility to edit all params
    // 3 – one identity with possibility to edit all params but not email address
    // 4 – one identity with possibility to edit only signature
    $ config [‘identities_level’] = 3;

    • 2018-02-01 at 08:49

      What does the mail.log show when you send authenticated from Thunderbird? Are you sure that you set the username for authentication correctly and not accidentally as the identity?

      • 2018-02-01 at 21:26

        I set up clients again and now it works fine on both. I’m sorry, it was my mistake.

  • 2018-02-05 at 11:54

    Hi !

    First of all, thanks for your tutorial, it’s really useful and complete!

    But, I have two remaining problems… I made everything like you, but I still have an SSL issue, and my mails aren’t crypted (which is a problem…). I have to say that I don’t understand where’s my error, because it should be errors in my conf. (I used LetsEncrypt, and write the path in the dovecot ssl file and postfix conf).

    I also can’t use the AUTH PLAIN, I have a “authentication failed” each time I try… (I try the perl command line). Maybe a smtp error? I don’t see anything in the log file linked to that.

    Hope you may help, and thanks for your tutorial!

    (I’m sorry for my English, I’m a French student 😉 )

  • 2018-02-09 at 23:14

    A simplest way to have a base64 encoded string is to use the base64 command in the shell :

    echo -n ‘ summersun’ | base64

    the result is :

    • 2018-02-12 at 08:22

      Thanks for the hint. However I get slightly different strings. Even your string is not exactly the same as what Perl outputs. I tried escaping the @ character as well as adding null bytes. Not sure what I’m missing.

  • 2018-02-14 at 10:34

    in other examples, you have put the strings to change in bold ( postconf smtpd_tls_cert_file=/etc/letsencrypt/live/ ) above and others in that section..


Leave a Reply

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.