Last active
December 17, 2015 13:39
-
-
Save kteru/5619086 to your computer and use it in GitHub Desktop.
ほぼ bash オンリーで smtp client
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
#!/usr/bin/env bash | |
PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/sbin:/usr/sbin | |
export PATH | |
# usage | |
_usage() { | |
echo "usage:" | |
echo " echo hogehoge | ${0} -t to@add.re.ss [-f from@add.re.ss] [-s subject] [-m mxhost] [-p mxport]" | |
exit 1 | |
} | |
# getopts | |
while getopts :t:f:s:m:p: OPT; do | |
case ${OPT} in | |
t) ENABLE_t="t"; VALUE_t=${OPTARG};; | |
f) ENABLE_f="t"; VALUE_f=${OPTARG};; | |
s) ENABLE_s="t"; VALUE_s=${OPTARG};; | |
m) ENABLE_m="t"; VALUE_m=${OPTARG};; | |
p) ENABLE_p="t"; VALUE_p=${OPTARG};; | |
:|\?) _usage;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
# check | |
[ "${ENABLE_t}" != "t" ] && _usage | |
# make params | |
MAIL_TO=${VALUE_t} | |
MAIL_FROM=${VALUE_f:-$(whoami)@${HOSTNAME}} | |
MAIL_SUB=${VALUE_s} | |
MAIL_BODY=$(cat) | |
SMTP_HOST=${VALUE_m:-$(dig +short $(echo ${MAIL_TO} | cut -d'@' -f2) mx | head -n 1 | cut -d' ' -f2)} | |
SMTP_PORT=${VALUE_p:-25} | |
FD=5 | |
# start | |
_fd=${FD} | |
eval "exec ${_fd}<>/dev/tcp/${SMTP_HOST}/${SMTP_PORT}" | |
RETVAL=255 | |
_cnt_250=1 | |
while read -r -u ${_fd} res; do | |
echo ${res} >&2 | |
case ${res} in | |
220\ *) | |
_req="EHLO ${HOSTNAME}\r\n" | |
echo -ne "${_req}" >&${_fd} | |
echo "--- sent: ${_req}" >&2 | |
;; | |
250\ *) | |
if [ ${_cnt_250} -eq 1 ]; then | |
_req="MAIL FROM: <${MAIL_FROM}>\r\n" | |
elif [ ${_cnt_250} -eq 2 ]; then | |
_req="RCPT TO: <${MAIL_TO}>\r\n" | |
elif [ ${_cnt_250} -eq 3 ]; then | |
_req="DATA\r\n" | |
elif [ ${_cnt_250} -eq 4 ]; then | |
_req="quit\r\n" | |
fi | |
echo -ne "${_req}" >&${_fd} | |
echo "--- sent: ${_req}" >&2 | |
_cnt_250=$((_cnt_250 + 1)) | |
;; | |
[0-9][0-9][0-9]-*) | |
: | |
;; | |
354\ *) | |
echo -ne "From: ${MAIL_FROM}\r\n" >&${_fd} | |
echo -ne "To: ${MAIL_TO}\r\n" >&${_fd} | |
echo -ne "Subject: ${MAIL_SUB}\r\n\r\n" >&${_fd} | |
echo "${MAIL_BODY}" >&${_fd} | |
echo -ne "\r\n.\r\n" >&${_fd} | |
echo "--- sent: <MAILDATA>" >&2 | |
;; | |
221\ *) | |
echo "--- closed" >&2 | |
RETVAL=0 | |
;; | |
*) | |
echo "--- error occured" >&2 | |
RETVAL=1 | |
;; | |
esac | |
if [ ${RETVAL} -ne 255 ]; then | |
exit ${RETVAL} | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment