Bash script to send SMTP email

UPDATE: at bottom (1.30.14)

So I’ve transitioned to a new position in San Diego where I’m more support/administration vs. incident handling/intrusion detection, and one of things I’ve recently and in the past have wanted was some sort of way to confirm the SMTP gateway’s for the company your working at are up and processing email from the internet.  Now of course you can telnet to port 25 manually but that’s a pain and the call that “your stuff is down” could come at anytime 24/7.  I’ve googled for a script like this many times over the years but never saw something that would do exactly what I wanted.  In the world of IT getting frustrated enough over and over is usually the only thing that motivates you to get off your azz and script up something yourself.

So I decided to put together a bash script that would send an email with telnet to me through each of the SMTP relays separately.  Also I wanted something I could simply launch from a Putty session to a free RedHat Amazon AWS instance anywhere I was w/o worrying about VPN’ing into work to troubleshoot, this would test the inbound internet connectivity part as well.  I added an if/then statement to allow me the option to include an email address on the command line of the person complaining my gear isn’t working.  So if the x number emails that pop into their inbox with date/time stamp equals the x number of relays the company owns then my servers are up and processing mail and they need to look elsewhere for the trouble.  Script is below in a .txt form, feel free to offer suggestions or share links to your own scripts in the blog comments as this comes with the usual disclaimer of me not being a bash scripting expert and use at your own risk, etc etc.

Script with some comments within the first server’s connection

sendtestemail_formattedforblog

Random Tips I’ve learned

1. If you are testing/modifying this script try running it with bash -x ./sendtestemail.sh. Helps troubleshoot what’s going on between script and the mail server as the SMTP conversation takes place.
2. Add “TZ=’US/Pacific’; export TZ” w/o quotes to your .bash_profile changing the timezone of your Amazon AWS instance to whatever Timezone your SMTP gateway’s are in.
3. When viewing the script use notepad++ and format the script as Language > S > Shell to better understand what’s going on.

4.  I think amazon is throttling outbound connections on port 25, as I’m having some trouble connecting to the fourth SMTP agent in my script, but I’m seeing no attempts on the FW so sounds like outbound blocks probably to combat SPAM.  So I modified the script with longer sleep times, and uploaded that here.

5. Use and buy JuiceSSH for Android!  I can now auth to the Amazon instance with pub/priv keys and launch the script to whoever is saying my stuff is down from my phone.  Very cool.