2013-10-23

Email from Command Line using bmail

Windows batch scripts can be used to perform a bunch of handy administrative tasks, like nightly backups.  Especially when you configure them to run via the OS Task Scheduler, 'Schedules Tasks' as it is called in most versions of Windows.  But to count on such automated task regularly you need to be able to see the output and history of such tasks.  The Task Scheduler isn't much help for this.  Instead, I prefer to email the task log to myself so that I can view and archive the results accordingly.

My overall strategy for such batch scripts it is to redirect the output of every command within the batch script to a log file, use > for a new file, and >> to append to the existing file.  Then I use bmail to email a copy of the log file to myself.

Bmail is a very handy command line email tool created by Craig Peacock.  (http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm)

So an oversimplified script I would craft would look something like this:

  date /t > C:\taskx\backup.log
  
  (task commands go here: e.g.)
  copy c:\sqlbu\*.bak "x:\bu-archive\sql\" >> C:\taskx\backup.log
  
  date /t >> C:\taskx\backup.log
  bmail -s smtp.runbooks.info -t admin@runbooks.info -f server-x@runbooks.info -a Task X -m C:\taskx\backup.log -c

BMail option are:
-s smtp server
-t To address
-f From address
-a Subject of message
-m file name that contain the body of message, the task log file that was created
-c Prefix above file with CR/LF to separate body from header

I note the date and the beginning and end of the task so I have an idea how long it takes.

Put the bmail.exe somewhere within your %PATH% locations, most likely C:\Windows\System32\, so that it universally accessible to all script you write.

Also, when you are copying backup files for archive purposes, (as this trivial snippet might suggest) you might also want to use forfiles to ensure that your archive of backup data doesn't grow indefinitely.

No comments:

Post a Comment