Tuesday, December 30, 2008

Automailer Batch Script using Blat

Quite sometime back we needed a simple way to inform our customers the status of their order, the system was able to generate a text file with the code of the customer but we still needed to figure out how to get it to them.


Instead of coding a complicated solution we decided to use a small batch script that did this job. We basically get all these files into a single folder and get the script to run every fifteen minutes to send across a mail to these customers with the file attached.

To enable this we use a small freeware program called blat. Its a command line mailer, a program that allows you to send a mail from the dos prompt.

Its available here

www.blat.net

The script works with a list that has the customer code in one line and the email addresses that the file needs to be sent to on the next line comma separated without any spaces. If a new customer is added, the code and email address would need to be added to the file

For this example the file is called customer.txt and the contents are in the following format

1234
abc@abc.com,def@def.com
5678
abc@abc.com,def@def.com,xyz@xyz.com

The script loops through all the files in the folder and picks up the email addresses it needs to send the email too and send it across. It then moves the file into the respective folder of the customer code.

To understand how it works, its important to understand how blat works. Blat needs to first be configured with the smtp server before the script works.

The usage is blat -savesettings

The normal usage is shown below and can be brought up by blat/?


The script is below


:start
echo off

rem This allows for the variable to work within a for loop
SETLOCAL ENABLEDELAYEDEXPANSION

rem This resets the variables used
set a=1
set rs=none

rem This is the loop that goes through for each file in the current folder and sets the
rem every line of the customer.txt to variable i
rem The variables a and b are used to alternate between the customer code and addresses
rem The rs variable is used to store the customer code on every alternative line of the txt file

for /f "tokens=*" %%i in (customer.txt) do (

if "!a!"=="1" set rs=%%i
if "!a!"=="1" set b=2
if "!a!"=="2" if exist *!rs!*.txt blat -t %%i -body "Order details" -s "Order report - !rs!" -attach *!rs!*.txt
if "!a!"=="2" if exist *!rs!*.txt move *!rs!*.txt !rs!
if "!a!"=="2" set b=1
if "!a!"=="2" set a=1
if "!b!"=="2" set a=2)
echo on

Hope you can get this script to work for you the way you want to. Do drop me a comment would love to hear from you.