7

How do I suppress blank emails? FOr e.g. in the following example, I will like to

some command | mail -s "tables altered on `hostname`" me@company.com

I get the following message "after" sending the message:

Null message body; hope that's ok

This is not ok. I do not want to send mail if there is no text.

shantanuo
  • 3,459
  • 8
  • 47
  • 64

5 Answers5

15
#!/bin/sh  

string=`some command`
len=${#string} 
if [ "$len" -gt "0" ]
   then echo $string | mail -s "tables altered on `hostname`" me@company.com
fi  

This will send the mail only if the output of the command is at least 1 character long, but this may include blanks etc.

(The solution above works, but is unnecessary. man mail reveals the -E option):

some command | mail -E -s "tables altered on `hostname`" me@company.com
Sven
  • 97,248
  • 13
  • 177
  • 225
8

I use the following:

$ mail --exec 'set nonullbody' -s Test test@example.com

Which I found in the GNU mail documentation under the nullbody section.

daharon
  • 401
  • 4
  • 6
2

For some implementations of mail the command line switch -E is equivalent to --exec which let's you execute a command. In this case daharon's answer works quite well. You can even shortened it to:

$ mail -E 'set nonullbody' -s Test test@example.com

If you want to test this behavior use the echo command with the -n command line switch to suppress the trailing newline.

This command sends an email:

$ echo -n "something" | mail -E 'set nonullbody' -s Test test@example.com

But this command doesn't send an email:

$ echo -n "" | mail -E 'set nonullbody' -s Test test@example.com
lukket
  • 21
  • 1
2

One-liner version of SvenW's answer (the creds should go to him, not me)

string=`some command`; [ "$len" -gt "0" ] && ( echo $string | mail -s "tables altered on `hostname`" me@company.com )
JeffG
  • 1,184
  • 6
  • 18
1

example:

echo -n "" | mail -E -s "Log Message" me@mydomain.tld

explain:

an empty string has endline character so we have to add -n to exclude in this testing echo \n (cr). But if your body message is not existing hence mail will exit/stop sending.

sources:

Why does mail -E let me send empty messages? http://heirloom.sourceforge.net/mailx/mailx.1.html

Dung
  • 141
  • 4
  • You're explanation falls a bit short, mainly because you're not actually answering the original question of how to suppress blank emails. - In my humble opinion you're missing something at the start of your answer along the lines of: *"Many implementations of `mail` support the `-E` command line switch which does `` and an `example of how you would improve the original command line`* and only then your explanation of how even `-E` is not quite foolproof.... – HBruijn Sep 13 '15 at 17:51