Installing mailx and configuring SMTP for sending emails in Linux

Publish: 2018-01-05 | Modify: 2018-01-06

The mail command is a tool for sending and receiving emails in a Linux environment. By default, mail uses sendmail to send emails, but sendmail is often seen as spam. It is recommended to use SMTP services instead of sendmail for more stability.

SMTP

Installing mail

By default, the mail command may not be installed. To install it, run the following command:

# CentOS
yum install -y mailx
# Debian or Ubuntu (untested)
apt-get -y install mailx

Configuring SMTP

By default, without any modifications, the mail command will use the built-in sendmail to send emails. The following steps will configure mail to use an external SMTP service.

  1. Edit the configuration file:
vi /etc/mail.rc
  1. Append the following content at the end of the file and save it:
set [email protected]
set smtp=smtp.exmail.qq.com
set [email protected]
set smtp-auth-password=35******3N
set smtp-auth=login
  • set from: Set the sender's email address.
  • set smtp: Set the external SMTP server.
  • set smtp-auth-user: Set the SMTP username (usually the full email address).
  • set smtp-auth-password: Set the SMTP password.

Testing the Email Sending

To test sending an email, use one of the following commands:

echo "this is my test mail" | mail -s 'mail test' [email protected]
# or
mail -s 'mail test' [email protected] < test.txt

Test Email

Using SSL/TLS

The above configuration sends emails in plain text, which poses security risks. Additionally, Gmail/Zoho and other email providers require the use of SSL/TLS encryption. To improve security, it is recommended to use SSL or TLS when sending emails.

  1. Find the local nssdb certificate path by running the following command:
find / -name "cert*.db"
  1. Modify the mail configuration file and use SSL encryption:
vi /etc/mail.rc
  1. Append the following content at the end of the file:
set [email protected]
set smtp=smtps://smtp.zoho.com:465
set nss-config-dir=/etc/pki/nssdb/
set ssl-verify=ignore
set [email protected]
set smtp-auth-password=htH*****T8
set smtp-auth=login
  • set nss-config-dir: Specify the local certificate path.
  • set smtp=smtps://smtp.zoho.com:465: Set the SMTP address and port. Note that smtps indicates SSL encryption.
  • set ssl-verify: Ignore certificate errors.

If you want to enable TLS encryption, append the following line and set the correct TLS port:

set smtp=smtp://smtp.zoho.com:587
set smtp-use-starttls=yes

Summary

Configuring the mail command with an external SMTP service can help with task notifications in shell automation and achieve higher delivery rates compared to using the built-in sendmail.

References:


Comments