Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edmondscommerce/61c55dd4e9335088a1676390be93f8b2 to your computer and use it in GitHub Desktop.
Save edmondscommerce/61c55dd4e9335088a1676390be93f8b2 to your computer and use it in GitHub Desktop.
BASH function to email via Gmail SMTP
# Bash function to send email via Gmail SMTP
# sendEmail [subject] [toEmail] [message] (optional attachment path)
function sendEmail(){
if (($# < 3 ))
then
echo ""
echo "Usage:"
echo "sendEmail [subject] [toEmail] [message] (optional attachment path)"
echo ""
exit 1
fi
local subject=$1
local toEmail=$2
local message=$3
local attachmentPath=${4:-''}
if [[ "" != "$attachmentPath" ]]
then
if [ ! -f $attachmentPath ]
then
echo "Error no file found at $attachmentPath"
exit 1
fi
fi
local fromEmail="info+$(hostname | xargs echo)@edmondscommerce.co.uk"
local fromName=$(hostname)
local gmailCertsPath=~/gmailCerts/
if [ ! -d $gmailCertsPath ]
then
echo "Setting up Certs"
local currentDir=$(pwd)
cd ~/
mkdir -p $gmailCertsPath
certutil --empty-password -N -d $gmailCertsPath
wget https://www.geotrust.com/resources/root_certificates/certificates/GeoTrust_Global_CA.cer
mv GeoTrust_Global_CA.cer $gmailCertsPath
echo -n | openssl s_client -connect smtp.gmail.com:465 -CAfile certs/GeoTrust_Global_CA.cer | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > GMAILCERT
certutil -A -n "Google Internet Authority" -t "C,," -d $gmailCertsPath -i GMAILCERT
certutil -L -d $gmailCertsPath
rm GMAILCERT
cd $currentDir
echo "done.."
fi
if [[ "" != "$attachmentPath" ]]
then
echo $message | mailx -v -s "$subject" \
-a $attachmentPath \
-S smtp-use-starttls \
-S ssl-verify=ignore \
-S smtp-auth=login \
-S smtp=smtp://smtp.gmail.com:587 \
-S from="$fromEmail($fromName)" \
-S [email protected] \
-S smtp-auth-password=PASSWORDHERE \
-S ssl-verify=ignore \
-S nss-config-dir=$gmailCertsPath \
$toEmail
else
echo $message | mailx -v -s "$subject" \
-S smtp-use-starttls \
-S ssl-verify=ignore \
-S smtp-auth=login \
-S smtp=smtp://smtp.gmail.com:587 \
-S from="$fromEmail($fromName)" \
-S [email protected] \
-S smtp-auth-password=PASSWORDHERE \
-S ssl-verify=ignore \
-S nss-config-dir=$gmailCertsPath \
$toEmail
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment