Sending Email Alert for SSH Logins / Linux / CentOS / Sending Email Alert for SSH Logins

Let’s look at how to send an email notification when logging into a Linux server remotely via SSH. We’ll use postfix to send email alerts and the Gmail SMTP server as a relay host.

Install the following packages on your Linux host:

  • Ubuntu/Debian:
    sudo apt-get install postfix mailutils -y
  • RHEL/Rocky Linux/CentOS/Oracle Linux:
    dnf install postfix mailx

When you install postfix, select Internet site mode and specify the FQDN of your host.

install and configure postfix

We will use the Gmail SMTP server to send emails. In order to authenticate to SMTP, you need to create an App password under -> Security -> App password -> Select Mail app.

get gmail app pasword

Create a password file:

sudo nano /etc/postfix/sasl_passwd

Add here the Gmail email address and the app password that was generated for you:


To make the file accessible only to the root user, change the permissions:

sudo chmod 600 /etc/postfix/sasl_passwd

Compile the contents of the sasl_passwd file:

sudo postmap /etc/postfix/sasl_passwd

Then open the postfix config file:

sudo nano /etc/postfix/

Change the value of the relayhost parameter:

relayhost = []:587

Add the following lines:

smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Restart the postfix daemon and add it to startup:

sudo systemctl restart postfix

sudo systemctl enable postfix

Open the /etc/profile file:

sudo nano /etc/profile

Add the following lines:

if [ -n "$SSH_CLIENT" ]; then
TEXT="$(date): ssh login to ${USER}@$(hostname -f)"
TEXT="$TEXT from $(echo $SSH_CLIENT|awk '{print $1}')"
echo $TEXT|mail -s "Alert SSH login"

Log out and reconnect to the Linux host via SSH. A notification of the remote connection should be sent to the specified email address. It will contain the user name and IP address from which the connection was made.

Leave a Reply

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