Skip to content

Instantly share code, notes, and snippets.

@borgand
Created June 28, 2010 08:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borgand/455580 to your computer and use it in GitHub Desktop.
Save borgand/455580 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Function to connect to SMTP and send mail to it
# returns:
# 0 - SUCCESS
# 1 - FAILURE: unable to complete session to DATA command
# 2 - FAILURE: problems after DATA command (server did not enqueue the message)
function bash_mail(){
# Default configuration
# Can be overridden by ARGV in order: TO, SUBJECT, MESSAGE, FROM, SERVER
TO=${1:-'me@example.com'}
SUBJECT=${2:-"Probleem ${HOSTNAME}"}
MESSAGE=${3:-'Panic! Come to rescue.'}
FROM=${4:-"root@${HOSTNAME}"}
SERVER=${5:-'mail.example.com'}
# start a subshell to aquire own set of filedescriptors
# Note! echo output must be redirected to 0, else it defaults to 1
(
# Compose all commands in an array
# starts from 1 to be in sync with reply codes (see below)
cmds=(
"HELO ${HOSTNAME}\r\n"
"MAIL FROM: $FROM\r\n"
"RCPT TO: $TO\r\n"
"DATA\r\n"
"From: $FROM\r\nTo: $TO\r\nSubject: $SUBJECT\r\n\r\n${MESSAGE}\r\n.\r\n"
"QUIT\r\n"
)
# expected reply codes in order
codes=( 220 250 250 250 354 250 )
# iterate over all commands
for (( i = 0; i < ${#cmds[*]}; i++ ))
do
# read input
read code msg <&0
# check that server replied with correct success code
if [ $code = ${codes[$i]} ]
then
echo -en ${cmds[$i]} >&0
else
break
fi
done
# workaround to deliver $i outside the subshell
exit $i
)<>/dev/tcp/$SERVER/25
# recatch the $i
i=$?
# result codes based on where the loop broke off
results=( [5]=2 [6]=0 )
# if defined, return from results array, else return 1
return ${results[$i]:-1}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment