Command Line Magic: Graphite, and Sending an email

Let’s take a look at sending an email from the Linux command line. How about we send a one-line email to ourselves? Note: The -s flag specifies the email’s subject.

$> echo "Hi friend!" | mail -s "This is an email"

Outside of this being really simple, there’s not much use to it, is there? Let’s do something more interesting: attaching an image to the email.

$> ( echo "Hi friend!" ; uuencode myimage.jpg myimage.jpg ) | mail -s "This is an email"

So what’s going on here? Not only are we placing our greeting (“Hi friend!”) within the body of the email, we’re also putting a uuencoded image in there. The way we’re using uuencode takes two parameters. The first myimage.jpg tells uuencode to encode the local file myimage.jpg. (This overrides the default behavior of reading from standard in.) The second myimage.jpg will be the name of the attachment within the email.

Is this more interesting? Yes. More useful? Maybe not. But let’s see if we can fix that.

How about we send an image from our monitoring solution (like Graphite).

$> curl --compressed > cpuUsage.png;
$> (echo "Recent CPU usage for `date`" ; uuencode cpuUsage.png cpuUsage.png ) | mail -s "CPU Usage for `date`" $

Throw that in cron, and you can get Graphite graphs emailed to you whenever you want.

Note: The command shown above probably doesn’t do everything you need it to. Think of it as inspiration. I mean, you’re going to need to log in to graphite because your monitoring isn’t exposed to the outside world. (Right?) Also, you may not want to retrieve a cached image. The final command, in all of it’s glory, is here.

$> cd /tmp; export AUTH=`curl -sv -u username:password "" 2>&1 | grep "Authorization: Basic" | awk '{print $4;}'` ;
$> curl '' -H 'Pragma: no-cache' -H 'Accept-Encoding: gzip,deflate,sdch'  -H 'Accept: */*'  -H "Authorization: Basic ${AUTH}" -H 'Connection: keep-alive' -H 'Cache-Control: no-cache' --compressed > /tmp/cpuUsage.png ;
$> (echo "Here is cpuUsage at `date`"  ; uuencode  cpuUsage.png cpuUsage.png )  | mail -s "CPU Usage - `date`"

Now, credit is owed where credit is due. I really wish I could claim credit for putting all of this together. But I can’t. This came from a co-worker who is known as our “command line guru”. I would link to his blog, if he had one.

Command Line Magic: Graphite, and Sending an email

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s