I have a cron job that if it fails outputs HTML. If it succeeds it outputs nothing, in which case I get no mail. If it does fail and write HTML, cron sends me the mail but it comes as plain text and is hard to read.

I came up with two partial solutions but have not figured out how to make it work really well. The first is to make my job print MIME specifiers at the top of the output, like this:

Mime-Version: 1.0
Content-Type: text/html

Then I run it like this in cron:

my-job | sendmail my.name

The main problem with this is I get mail even if there is no text at all. A secondary problem is that I had to add the MIME type lines to my script, which is sort of the wrong place for it (not elegant, but maybe tolerable).

Then I tried using mail or mailx, which have a -E option to skip sending if there is no text:

my-job | mail -E my.name

That does pretty much what cron does by default. Yet I can't figure out any way to set the MIME type with mail/mailx! Some references online say it is done using the -a option, but on my system (Fedora 16), mail -a takes an attachment filename, not a header line like Content-Type: text/html as it apparently does on some other systems.

I don't want to make a temporary file, check its size, etc. I think I want one of these:

  • A way to make cron mail readable as HTML.
  • To make sendmail skip empty messages.
  • To set a MIME type in mailx.
  • Some other approach using a different program which is installed by default on Fedora.
  • when you say plain text, do you mean html source code? – ctrl-alt-delor Sep 20 '12 at 8:07

Instead of specifying the recipient on the command line, call sendmail with -t and have your script generate a to: header. (You might as well do a subj: header while you're at it.) Then when there's no output, there's no recipient, and thus no mail.

| improve this answer | |

The easiest way would be to call sendmail fom within your script. That way you can control whether or not any mail is sent to you.

Alternatively, you could make your script return a success code if it fails and run sendmail only if the script exits "correctly":

$ my-job >/tmp/message && cat /tmp/message | sendmail 

The && tells bash to run the next command only if the first exited successfully (exit 0 in BASH or exit(0) in PERL). By telling your script to exit with status 0 if it fails, you will make the sendmail command be run only on failure.

| improve this answer | |

You can specify the content type as follows:

mail -s "$(echo -e "Status Report: $HOSTNAME\nContent-Type: text/html")" "yourmail@"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.