How to Send Email from a Linux Server (msmtp for Alerts and Cron Output)

Let your server email you: msmtp: tiny, uses the mail account you already have.

A server that can email you is a server that tells you when a backup fails, a disk is nearly full or an update rebooted it. Running a full mail server is a nightmare; msmtp is the opposite — a tiny program that hands mail to an SMTP service you already have (Gmail, Outlook, Fastmail, your web host) and makes sendmail work for every other tool.

Quick reference

TaskWhat
Installsudo apt install msmtp msmtp-mta mailutils -y
Config/etc/msmtprc (chmod 600)
Test`echo "test"mail -s "Hello from server" you@example.com`
Cron output to emailMAILTO=you@example.com at the top of the crontab
Log/var/log/msmtp.log

1. Get SMTP details

A dedicated address just for the server (myserver@gmail.com) keeps your main account out of it.

2. Install and configure

sudo apt install msmtp msmtp-mta mailutils -y
sudo nano /etc/msmtprc

defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile /var/log/msmtp.log

account default
host smtp.gmail.com
port 587
from myserver@gmail.com
user myserver@gmail.com
password your-app-password

sudo chmod 600 /etc/msmtprc
sudo touch /var/log/msmtp.log && sudo chmod 666 /var/log/msmtp.log

msmtp-mta makes msmtp answer to the name sendmail, which is what cron, unattended-upgrades and most scripts use.

3. Send a test

echo "The server can email." | mail -s "Hello from $(hostname)" you@example.com

Check your inbox (and spam). If nothing arrives, tail /var/log/msmtp.log says why.

4. Get cron output by email

At the top of crontab -e (and sudo crontab -e):

MAILTO=you@example.com

Now anything a cron job prints is emailed to you. Jobs that print nothing send nothing, so only the chatty or failing ones reach you.

5. Other things that now work

A disk-space alert in one line

*/30 * * * * [ $(df / --output=pcent | tail -1 | tr -dc '0-9') -gt 85 ] && df -h | mail -s "Disk over 85% on $(hostname)" you@example.com

Troubleshooting

"authentication failed". Wrong app password, or you used your normal Gmail password. Gmail requires app passwords for this.

Email arrives in spam. The From address should be the same account you're sending through. A dedicated address for the server helps too.

"sendmail: command not found". msmtp-mta isn't installed.

Works by hand, not from cron. Cron runs as root and reads /etc/msmtprc fine; check MAILTO is at the top and the job actually prints something.

Wrapping up

One config file, one app password, one test email. From then on cron, updates, Fail2ban and your own scripts can all reach you, which is the difference between finding out about a failed backup tonight and finding out the day you need it.

Call us