Does my Server Talk to Me?

Red smoke signal

Installing an SMTP Mail-Forwarding Service in Ubuntu

Does your server talk to you?

Mine does.

I have to admit: I kind of like it.

Perhaps I need to make more real-life friends?

Jury is still out on this one.

In any event I am happy that my computers now have the ability to e-mail me when problems occur, when things happen in the background that require my attention among other things.

For this tutorial I will help walk you through the steps I took to configure PostFix on my Linux server. There are a large number of existing articles out there that describe how to set up PostFix on Linux. I found most of them helpful; at the same time I felt that I needed my own set of descriptive steps to help walk me through how to configure this service.

Postfix is used as the mailer agent and Gmail is used for SMTP mail service.

First Steps

Start by updating your system:

sudo apt-get update && sudo apt-get upgrade

Install Postfix and the libsasl2-modules package:

sudo apt-get install libsasl2-modules postfix

During the installation you should see a prompt, hit tab then Enter to go to the next screen.

Hit Tab then Enter to select the default ‘Internet Site’.

Leave the default for the system mail name, in my case it is <hostname>.localdomain, hit Tab then Enter to proceed with the setup.

If you are not sure about the fully-qualified domain name (FQDN) you can query it once you are back at the prompt via:

hostname -A

Generate App Password

If you have 2-factor authentication enabled for your G-mail and other parts of your Google account, you will need to generate an application password for Postfix to be able to send e-mails using your G-mail account.

Follow the steps outlined here to generate an app password. Keep your newly-generated app password in a safe place as you will need it when configuring Postfix in subsequent steps. The article also contains additional troubleshooting for “less secure apps” access. I found that I did not require any additional troubleshooting but you may wish to keep this in your back pocket in case you encounter problems.

Edit Hostname

Full-disclosure, I found that working version of the configuration file for Postfix is a bit confusing, with parameters spread across it. There is apparently a more-detailed version available, see the comment at the top of the configuration file for the path to this more-detailed file.

Enter the postfix configuration to make several changes:

sudo nano /etc/postfix/main.cf

Confirm the myhostname parameter is set properly:

myhostname = <hostname>.localdomain

Send-Only

For my setup I only want my server to be able to send e-mails, I do not think my system will care that much if people try sending it stuff. Edit the main.cf by commenting out the existing line for inet_interfaces and changing it to loop-back only mode as follows:

# Modified YYYY-MM-DD by <author> to allow outgoing mail only.
#inet_interfaces = all
inet_interfaces = loopback-only

Relay

Update the relayhost parameter to the SMTP mail service of your choice, in my case I use Google:

 # Modified YYYY-MM-DD by <author>.
relayhost = [smtp.gmail.com]:587

Encryption

Enable STARTTLS encryption by changing it from may to encrypt:

# Modified YYYY-MM-DD by <author>.
# Enable STARTTLS encryption
#smtpd_tls_security_level=may
smtp_tls_security_level = encrypt

There is a second line in the configuration for the tls security level, you will want to comment-out this line otherwise Postfix will generate a warning when the service is run:

# Modified YYYY-MM-DD by <author>.

#smtp_tls_security_level=may

Configure additional parameters for encryption and security as follows:

# Modified YYYY-MM-DD by <author>.
# Use TLS, see https://askubuntu.com/questions/906394/how-to-configure-mail-etc-file/906431#906431
# as well as https://serverspace.io/support/help/postfix-as-a-send-only-smtp-on-ubuntu/
smtp_use_tls = yes

# Enable SASL authentication
smtp_sasl_auth_enable = yes

# Disallow methods that allow anonymous authentication
smtp_sasl_security_options = noanonymous

# Location of sasl_passwd
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd

# Location of CA certificates
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

# Limit header size
header_size_limit = 4096000

Prepare Credentials

Create a new file and place your credentials via:

sudo nano /etc/postfix/sasl/sasl_passwd

In this new file, insert the following line:

[smtp.gmail.com]:587 <email_username>@gmail.com:<app_password>

Use the app password you generated in the Generate App Password step.

Hit Cntl-O to save, Cntl-X to close.

Postfix needs your SMTP credentials to be encoded with elevated priviledges, you can do this via:

sudo postmap /etc/postfix/sasl/sasl_passwd

Both of these new files contain your credentials in plain-text, I highly recommend you change their permissions to help keep these files away from prying eyes, see this post for details:

sudo chown root:root /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db
sudo chmod 0600 /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db

Test Postfix

Prior to performing any tests, restart Postfix via:

sudo systemctl restart postfix

Send a test e-mail using sendmail:

sendmail <recipient>@<address>.com
From: <email_username>@gmail.com
Subject: Test
Testing 123!
.

Be sure to type . in order for the e-mail to send.

You will have to write the above lines manually: when you are finished typing your draft e-mail you can send it by placing a period on the last line followed by hitting Enter.

Give it some time for the e-mail to send, you can check your Sent folder in G-mail to ensure it was sent. Check the recipient’s folder for the test e-mail a few moments later.

Congratulations! If all goes well you should have a shiny new e-mail waiting for you in your mailbox.

Aliases are Good for Mail Re-direction

The above steps are all fine and good but they will not be of much use until we set up some aliases. Most system messages are sent to root, so we need to set up two aliases. See this post for details. One for messages to be sent from root to a <local_user>, and a second alias from <local_user> to <destination_username>@<destination_address>.com.

First stop Postfix to help prevent potential errors when aliases are being configured:

sudo systemctl stop postfix

Next create a aliases file via:

sudo nano /etc/aliases

Once in the file, put the following lines:

postmaster: root
root: <local_user>
<local_user>: <email_username>@gmail.com

Hit Cntl-X to save, Cntl-O to exit.

Apply the changes via:

sudo newaliases

You may get an error such as:

postalias: fatal: open database /etc/aliases.db: Permission denied

If this happens, try deleting and then re-creating the aliases file. See this post and this one for additional troubleshooting.

With the new aliases in place, any messages such as errors or system messages directed to root should be forwarded to the e-mail you have specified.

Mail forwarding is useful in cases such as, oh I don’t know, when a user tries to unsuccessfully log-in to your SuperUser account. It might help to keep yourself in-the-know in these situations!

Re-start Postfix prior to sending any new e-mails:

sudo systemctl restart postfix

Send a test e-mail to root to ensure it is forwarded to the address you specified in the aliases file:

sendmail root

Put something in the body of the e-mail such as ‘tes123’, press enter then send the e-mail by typing:

.

Yes, you read that correctly: a single . That’s it!

Check your inbox to ensure the test message was delivered.

Bonus: Configure Cron to Mail Notifications

I am a huge fan of cron, it helps me run my scripts in the background. What more could I ask for? How about sending me an e-mail when a task has completed? With all of the above steps completed, this is now possible.

Edit the crontab for your user via the following command:

crontab -e

Once in the file, add the following line close to the top:

# Added YYYY-MM-DD by <author>.
MAILTO=root

Hit Cntl-X to save, Cntl-O to exit.

With the above line added to your user’s crontab and provided all of the above steps to configure postfix were completed properly you should receive an e-mail for each task completed by cron. Go ahead and schedule a test task within the next minute or two to confirm this works too! That’s a lot of toos…

I found the following helpful article as it provides some additional troubleshooting for automatic mailing.

Troubleshooting Stale Credentials

Everything worked fine with the above set-up steps until one day my server stopped sending e-mail.

I found this post helpful. Try issuing the following command to see if e-mail is being sent:

mailq

When I ran this command a bunch of lines appeared indicating there was a problem:

4B2A91240187 1130 Thu Feb DD HH:MM:SS <server_name>@<server_domain>.localdomain
(delivery temporarily suspended: SASL authentication failed; server smtp.gmail.com[XXX.XX.XXX.XXX] said: 535-5.7.8 Username and Password not accepted. Learn more at?535 5.7.8 https://support.google.com/mail/?p=BadCredentials s11-20020a37a90b000000b005f1806cbfe4sm5620397qke.42 - gsmtp)
recipient@yahoo.ca

Hmm.

Well that’s not good.

I ended up re-generating my app password per the above steps, in addition to preparing credentials. With these steps completed I was able to send myself a test e-mail although it took a few moments for the e-mail to come through. Success!

Troubleshooting Unreachable Network

If your Postfix is still struggling you can inspect the mail log to see any recent activity:

nano /var/log/mail.log

I noticed something off:

May 11 09:54:54 postfix/smtp[167386]: connect to smtp.gmail.com[XXXX:XXXX:XXXX:XXX::XX]:587: Network is unreachable

According to this post the protocol in /etc/postfix/main.cf should be set to ipv4. Newer versions of postfix default to all which may lead to problems.

Edit the config via:

sudo nano /etc/postfix/main.cf

# Modified YYYY-MM-DD by <Author>
#inet_protocols = all
inet_protocols = ipv4

Hit Cntl-O to save, Cntl-X to close.

Re-start Postfix prior to sending any new e-mails:

sudo systemctl restart postfix

Re-inspect the log at a later date to see if the error is resolved.

Postscript

That’s it! Your system should now be configured to send e-mails to an address of your choosing. What do you think? Is having your computer talk to you something you’ve always wanted but were not sure how to ask? What are your experiences with these types of e-mail services?

Leave a Comment

Required fields are marked *