Linux (Ubuntu) Postfix to Send an Email
First install postfix, run the following command:
sudo apt install postfix
Now install mailutils, run the following command:
sudo apt install mailutils
Now open the postfix configuration file by using:
sudo nano /etc/postfix/main.cf
Find ‘relayhost’ and give it ‘[smtp.gmail.com]:587 like:
relayhost = [smtp.gmail.com]:587
Now add the following lines at the end of the file:
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
smtp_sasl_auth_enable = yes
smtp_tls_security_level = encrypt
smtp_sasl_security_options = noanonymous
There can be two variables ‘smtp_tls_security_level’ already in the file. Make sure to comment them by adding a ‘#’ at the start of that line.
Now make a file named ‘sasl_passwd’ in the ‘/etc/postfix/sasl’ directory:
sudo touch sasl_passwd /etc/postfix/sasl
Open that file and add the following line in that file:
[smtp.gmail.com]:587 [email]:[password]
Make sure your google account has two-factor authentication active. Also go to the ‘App Passwords’, Give the app name ‘smtp’ and create an app password. Copy that password and paste the password in the place of password of the ‘sasl_passwd’ file.
Now convert the ‘sasl_passwd’ file into a db file:
sudo postmap /etc/postfix/sasl/sasl_passwd
For the security, change the file ownership if you want to:
#Change ownership
sudo chown root:root /etc/postfix/sasl/sasl_passwd
#Change permission
sudo chmod 600 /etc/postfix/sasl/sasl_passwd
Now start the postfix service:
#Start service
sudo systemctl start postfix.service
#check service status
sudo systemctl status postfix.service
To send the email:
echo "message" | mail -s "Subject" email@gmail.com
Check your gmail: