Last updated on Monday 28th of February 2022 08:52:48 PM

HOW TO SEND E-MAIL FROM BASH


#!/bin/bash

#############################################################################
#
# Minimal e-mail client
# By Daniel J. Garcia Fidalgo (33HOPS) daniel.garcia@33hops.com
# Copyright ©2013 33HOPS, Sistemas de Información y Redes, S.L.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# http://www.gnu.org/licenses/gpl-3.0.en.html
#
#############################################################################

##################################################
## Dependencies: base64, nc
## CONFIGURABLE VARIABLES
##################################################

HOSTNAME="mydomain.com"
smtpsrv="smtp.mydomain.com"
smtpport="25"
smtpusr="$( echo -ne me@mydomain.com | base64 )"
smtppwd="$( echo -ne m|passw0rd | base64 )"
mailfrom="me@mydomain.com"
mailto="me.myself@mydomain.com"
subject="HELLO AGAIN"

emailHTMLStr="
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n
<html>\n
<body>
THIS IS THE E-MAIL BODY, MAY BE REPLACED WITH A VARIABLE
</body>
</html>\n
"


##################################################
## END OF CONFIGURABLE VARIABLES
##################################################

newline=$'\012'
function err_exit() { echo -e 1>&2; exit 1; }

function mail_input {
echo -ne "helo ${HOSTNAME}\r\n"
echo -ne "ehlo ${HOSTNAME}\r\n"
echo -ne "AUTH LOGIN\r\n"
echo -ne "${smtpusr}\r\n"
echo -ne "${smtppwd}\r\n"
echo -ne "MAIL FROM: <${mailfrom}>\r\n"
echo -ne "RCPT TO: <${mailto}>\r\n"
echo -ne "DATA\r\n"
echo -ne "Content-type: text/html\r\n"
echo -ne "From: <${mailfrom}>\r\n"
echo -ne "To: <${mailto}>\r\n"
echo -ne "Subject: ${subject}\r\n"
echo -ne "\r\n"
echo -ne ${emailHTMLStr//\\n/$newline}"\r\n"
echo -ne ".\r\n"
echo -ne "quit"
}

# You may directly send the protocol conversation via TCP
# mail_input > /dev/tcp/$smtpsrv/$smtpport || err_exit

# If you have nc (netcat) available in your system this
# will offer you the possibility to observe the protocol
# conversation on screen

# mail_input | nc $smtpsrv $smtpport || err_exit

# If on addition you have OpenSSL you can send your e-mail under TLS

mail_input | openssl s_client -starttls smtp -connect ${smtpsrv}:${smtpport} || err_exit



Daniel J. García Fidalgo
33HOPS