Send emails using the command line for fun and profit!
Posted on
September
4, 2020
Here are a few reasons why:
-
send yourself and other people notification of cronjobs, scripts runs, CI jobs, etc.
-
leverage the POSIX pipe
|
, and pipe emails away! -
because you can.
Reason 3 is the fun part, reasons 1 and 2 are the profit part.
First install and configure SSMTP for using, say, Gmail as the email server:
Now install GNU Mailutils (sudo apt-get install mailutils
or the
equivalent on your OS), and send yourself your first email:
1
echo body | mail -aFrom:email@example.com email@example.com -s subject
And that’s about it, you’ve got mail. Here are some more places where it might be applicable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# report a backup cronjob, attaching logs
set -e
finish() {
status=$?
if [[ $status = 0 ]]; then
STATUS="SUCCESS (status $status)"
else
STATUS="FAILURE (status $status)"
fi
mail user@example.com \
-s "Backup job report on $(hostname): ${STATUS}" \
--content-type 'text/plain; charset=utf-8' \
-A"$LOG_FILE" <<< 'The log report is in the attachment.'
}
trap finish EXIT
do-long-backup-cmd-here
…and so on.
You may consider adding a alias mail='mail -aFrom:email@example.com'
so you
don’t keep re-entering the “From: “ part.
Send yourself some emails to see it working!