One of the things I wanted to do for the OwnCloud project was to send myself a daily e-mail with some key things. Initially, I just did this one at a time, and I would get multiple e-mails. This a Raspberry Pi, which is basically just Debian Linux – so the script stuff below should at least work with Debian, and its’ variants.
First Script: The basics
I initially had a script that looked like this:
This works, if you set up an SMTP server. This sent me two separate e-mails – and I schedule this in /etc/cron.daily.
However, I wanted to get one e-mail with multiple attachments. I typically use Microsoft Outlook, so having this send the “text” as the body of the message also meant that the formatting was always messed up too:
I can of-course fix that in Outlook, but I wanted to fix this at the source. So, how do you send e-mail with attachments, from Linux?
Second Script: Single attachments
The first thing I learned is that you need “uuencode”. To install that, you can do a:
sudo apt-get install sharutils
Then, you use it by piping data to it – or the first argument can be a source file name. Note that the “” is just a line continuation character so that I can continue on the next line:
So in the above case, I’m echoing (printing to stdout) the string “Attachment contents”, and piping that to uuencode, which prepares it as an attachment. Then, THAT is piped to the mail command.
Sure enough, that works as expected – I get an e-mail with the text as an attachment named “filename.txt”:
FInal Script: Multiple attachments:
Ok, it’s get a bit more complicated for more attachments. For that, I found it’s just easier to generate some files, and uuencode the files together, like this:
As you can see, you wrap your uuencode statements in parenthesis, and each element is “;” separated. You can include a message body too, by making that the last argument and simply echoing that as plain-text to stdout. Then, you pipe all of that to mail, and that will treat those as attachments:
and if I click on one of the attachments, it shows, correctly-formatted:
There are a handful of other things I’d like to get a status on. I now have a mechanism for doing that. I can now just expand on this script and add additional attachments. If it helps, here is the scripts for at least these two things, from above:
echo “Failed auth log: $failedAuth”
echo “Disk space log: $diskSpace”
echo “Getting failed login attempts…”
sudo grep “Failed password” /var/log/auth.log > $failedAuth
echo “Getting disk space…”
sudo df -H > $diskSpace
echo “UUEncoding and sending email…”
(uuencode $diskSpace disk-space.txt;
uuencode $failedAuth failed-auth.txt;
echo “Todays update.”) |
mail -s “ocrcs: Status” -t firstname.lastname@example.org