Monday, March 28, 2011

How to email from batch file using Gmail









I'm a big fan of Gmail and Google Apps. During my day job I've wanted the ability to send an email as part of a batch file. So I thought I'd document my steps, mostly for my future reference, but if it will help you also, then all the better. I suppose I should start by saying I'm running 64-bit Windows 7, so my steps will cater to that specific environment. Let's begin... 1. Download and install "Stunnel" from www.stunnel.org 2. Download "Blat" from www.blat.net. There isn't a regular install for this program. It can be run from from a command line. I'll describe both the "setup" and how to run it below. You will end up with a copy of the Blat.exe program in the same location as your batch file. 3. Configure Stunnel with these settings for Gmail (same for Google Apps):
client=yes

[imaps]
accept = 143
connect = imaps.gmail.com:993

[ssmtp]
accept = 25
connect = smtp.gmail.com:465
I have IMAP turned on for my Google Apps account. If you prefer to use POP3, I believe you will want to replace the "[imaps]" section with:
[pop3s]
accept  = 110
connect = pop.gmail.com:995
4. If you wish to run Stunnel as a service in windows, run the following command from the install folder for Stunnel:
stunnel -install
5. Create a "profile" for Blat by entering the following command:
blat -install localhost name@address.com@127.0.0.1:1109
Be sure you use your email address and tack on "@127.0.0.1:1109" on the end of it. 6. And now, the command to put into the batch file to send an email:
blat - -body “The test was completed successfully.” -to send_to_email -subject “Blat Test Successful” -server localhost -p smtp -u your_email_address -pw your_password
NOTE: your_email_address must be a valid Gmail or Google Apps email account.