Sometimes we require bash script to perform some operation and use a remote mail server to send mails. In this instance we require smtp authentication for the remote server to allow this operation.
The script was copied from the link http://linuxshellaccount.blogspot.com/2008/04/shell-script-to-send-mail-using-bash.html which describes networking with the help of file descriptors.
I just added a smtp authentication part.
Please ensure that others do not have access to your bash history for security reasons.
Usage
sh mail.sh report@yourserver.com youremail@gmail.com yourserver.com yourmailserver.com filecontainingmessage email@yourmailserver.com youremailpassword SCRIPT CONTENTS:
mail.sh
#!/bin/bash
#
# mail.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
# 2010 - Rayber
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#
if [ $# -ne 7 ]
then
echo "Usage: $0 FromAdress ToAdress Domain MailServer MailTextFile AuthEmail AuthPass"
exit 1
fi
from=$1
to=$2
domain=$3
mailserver=$4
mailtext=$5
authemail=`echo $6|openssl enc -base64|awk 'sub("..$", "")'`
authpass=`echo $7|openssl enc -base64|awk 'sub("..$", "")'`
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 "auth login" >&9
read -r temp <&9
echo "$authemail" >&9
read -r temp <&9
echo "$authpass" >&9
read -r temp <&9
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
When you run the script you should get a output similar to the following output.
235 2.7.0 Authentication successful
250 2.1.0 Ok
250 2.1.5 Ok
354 End data with
.
250 2.0.0 Ok