Friday, April 18, 2008

Shell Script To Send Mail Using Bash File Descriptors

Hey There,

It's the weekend again, and I thought I'd wrap up this week's postings with quick script that, again, demonstrates a great way to take advantage of networking with bash using file descriptors on Linux or Unix. If you find this sort of thing fascinating (which I seem to ;), be sure to check out our orignal post on networking with bash file descriptors and the follow up regarding more things you can do with bash networking.

Note: Interestingly enough, apart from file descriptors 0, 1 and 2, you should also stay away from file descriptor 5. It seems bash uses this as its default file descriptor when a child process is created. Thankfully, I chose the number 9 (No Beatles pun intended ;)

Today's script sends email from the shell, directly to port 25 out, and is simple to run. It only takes a few arguments: Your From address, your To address, your mail server or relay, your domain and your message text (which you can put in any sort of file, as long as it's readable).

Ex:

host # ./mail.sh me@xyz.com you@xyz.com xyz.com localhost fileName


Hope you enjoy it and find some good use for it. If anything, it might make shooting emails out from the shell when you have a good idea much easier (before you have to fuss with Windows and lose your train of thought - Does that happen to everyone else, or just me ;).

Have a great weekend :)


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash

#
# mail.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

if [ $# -ne 5 ]
then
echo "Usage: $0 FromAdress ToAdress Domain MailServer MailText"
exit 1
fi

from=$1
to=$2
domain=$3
mailserver=$4
mailtext=$5

if [ ! -f $mailtext ]
then
echo "Cannot find your mail text file. Exiting..."
exit 1
fi

exec 9<>/dev/tcp/$mailserver/25
echo "HELO $domain" >&9
read -r temp <&9
echo "$temp"
echo "Mail From: $from" >&9
read -r temp <&9
echo "$temp"
echo "Rcpt To: $to" >&9
read -r temp <&9
echo "$temp"
echo "Data" >&9
read -r temp <&9
echo "$temp"
cat $mailtext >&9
echo "." >&9
read -r temp <&9
echo "$temp"
echo "quit" >&9
read -r temp <&9
echo "$temp"
9>&-
9<&-
echo "All Done Sending Email. See above for errors"
exit 0


, Mike