6

I have postfix mail agent installed and I've configured gmail relay and I could send mails from the terminal as below:

root@statino1:~# mail -s "subject_here" [email protected]
CC: <hit enter for empty cc>

Type the mesage here
press Ctrl+d

I have to send a log file contents as a mail and schedule it to run everyday.

How do I send log file contents as mail message, how do I automate the inputs of mail command? so that I can schedule it. Anybody has any idea?

user3215
  • 5,293
  • 14
  • 52
  • 59

1 Answers1

5

You can send an email with one command like this:

mail -s 'Subject' [email protected]  < log.txt

mail expects a stream of input, if there is none, it gets standard input (i.e. it let's you type something). The < operator (unix file-stream) tells mail to read the contents of the file, rather than /dev/stdin (which is just a file as well).

Adding an attachment seems a little more difficult:


If you want to check if the file is empty or not, you can do a test like this:

if [ -s test.txt ];
then
    echo "file is not empty";
fi

So your command would look like this:

if [ -s log.txt ]; then mail -s 'Subject' [email protected]  < log.txt; fi
Stefano Palazzo
  • 85,787
  • 45
  • 210
  • 227
  • wow, will it skip cc:? I want it to be skiped. I'll give a try and let you know! – user3215 Mar 08 '11 at 13:38
  • Worked perfectly!. One more thing, is it possible to fine tune to send only if the log file is not empty. i.e if logfile has something in it then send, like checking the size of the file or something – user3215 Mar 08 '11 at 13:59
  • 1
    @user3215 of course, you can test if a file has something in it, I've added it to the answer. (please let me know if it works) – Stefano Palazzo Mar 08 '11 at 14:37
  • 1
    Awesome!!!. it works. when I checked syslog file without any mail command it didn't print "file is not empty". I checked your last line editing it and it worked perfectly. Thanks a lot!. The admins like you eases others life, otherwise I would have to spend months searching for this with what key word? don't know. Any way thanks again – user3215 Mar 09 '11 at 05:12