Sunday, October 14, 2007

Using Cron To Send Out Raw Email

Hey there,

It's been a while since work hasn't gotten in the way of my blog-baby here ;) Unfortunately, I've been on-call and it's taken every moment of my time. I'll be handing off the pager here in just about an hour. Yay!!

Got a question about how to use "cron" to send out emails without calling a separate script and using a linux/unix built-in mailer. It's actually very simple to do; it just looks complicated.

For instance, if you wanted to send out an email every 30 minutes on the hour and half hour, with a Subject of "Your Regular Email" and a body with just a few lines in it, like:

Hope you like this email!

, Mike"

You could just add this entry to your crontab:

0,30 * * * * (echo "Subject: Your Regular Email";echo;echo "Howdy";echo " Hope you like this email";echo;echo " , Mike")|/usr/lib/sendmail

It's a simple concept - You create the email on the left side of the pipe (|) and use sendmail on the right side to mail that out to the address (

The most important thing to remember is to write out the entire contents of your email in a subshell (in parentheses). If you wrote all those echo statements outside of a subshell, only the last echo would get passed to Sendmail, and you'd get an email with no subject and a body that said:

" , Mike"

Generally, you only send mail this way for really simple stuff, but it can be as complicated as you like :)

, Mike