Last active
August 21, 2018 07:58
-
-
Save edmondscommerce/61c55dd4e9335088a1676390be93f8b2 to your computer and use it in GitHub Desktop.
BASH function to email via Gmail SMTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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