Automated email of attachments

It is quite easy to email security or traffic reports automatically. We will use mpack, sendmail, and cron, but certainly the techniques could be combined with other utilities. The challenge with emailing files is that you have to encode the attachments into the email message using MIME. For the nitty gritty on MIME, see http://www.nacs.uci.edu/indiv/ehood/MIME/MIME.html.

First, let’s pack up the file we wish to send. Get a copy of mpack from http://ftp4.de.freesbie.org/pub/misc/mpack/ if you don’t already have it. There are binaries, but compiling/installing for us on Linux was as simple as running make and copying the binary to /usr/bin.

Let’s say the file we want to send is /usr/tmp/nightly.txt. To create an email named /usr/tmp/nightmail with the file nightly.txt as an attachment and a subject of nightstat:
mpack -s nightstat -o /usr/tmp/nightmail /usr/tmp/nightly.txt

[root@u-1 tmp]# cat nightly.txt
10  listening
20 horror
30 fix horror now
[root@u-1 tmp]#
[root@u-1 tmp]# mpack -s nightstat -o /usr/tmp/nightmail /usr/tmp/nightly.txt
[root@u-1 tmp]# ls -l
total 8
-rw-rw-r--    1 root     root           42 Sep 13 10:38 nightly.txt
-rw-rw-r--    1 root     root          557 Sep 13 10:47 nightmail
[root@u-1 tmp]#
[root@u-1 tmp]# cat nightmail
Message-ID: <28530.1000403278@u-1.signalq.com>
Mime-Version: 1.0
Subject: nightstat
Content-Type: multipart/mixed; boundary="-"
This is a MIME encoded message.  Decode it with "munpack"
or any other MIME reading software.  Mpack/munpack is available
via anonymous FTP in ftp.andrew.cmu.edu:pub/mpack/
---
Content-Type: application/octet-stream; name="nightly.txt"
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="nightly.txt"
Content-MD5: RoK4ggHUnLFMrZA2emnmsg==
MTAgIGxpc3RlbmluZwoyMCBob3Jyb3IKMzAgZml4IGhvcnJvciBub3cK
-----
[root@u-1 tmp]#

To send the mail, use:
[root@u-1 tmp]# sendmail webmaster@yourdomain.com < /usr/tmp/nightmail

Finally, just set this up in your crontab to mail the results nightly:
0 1 * * * mpack -s nightstat -o /usr/tmp/nightmail
0 2 * * * sendmail webmaster@yourdomain.com < /usr/tmp/nightmail

This will pack the stats at 1am and mail them at 2am every day.