Skip to content

Instantly share code, notes, and snippets.

@ypchen
Last active June 17, 2025 00:47
Show Gist options
  • Save ypchen/5b1b1af9750cb54b6e1e88fe9a91d2f7 to your computer and use it in GitHub Desktop.
Save ypchen/5b1b1af9750cb54b6e1e88fe9a91d2f7 to your computer and use it in GitHub Desktop.
send a message to Mailgun
#!/bin/bash
# --------------------
# default
# --------------------
if [ -z "${GIST_CONF+x}" ]; then
GIST_CONF="${HOME}/.Mailgun.conf"
fi
echo "GIST_CONF=${GIST_CONF}"
# mg_domain, api_key, MSG_SUBJ_PREFIX, MSG_FROM_EMAIL, & CURL if necessary
source ${GIST_CONF}
# --------------------
if [ -z ${CURL+x} ]; then
CURL="/usr/bin/curl"
fi
if [ -z ${to_email+x} ]; then
to_email="${1}"
fi
if [ -z ${MSG_SUBJ_PREFIX+x} ]; then
MSG_SUBJ_PREFIX=""
fi
if [ -z ${subject+x} ]; then
subject="${MSG_SUBJ_PREFIX}${2}"
fi
if [ -z ${text+x} ]; then
text="${3}"
fi
if [ -z "${4}" ]; then
from_email="${MSG_FROM_EMAIL}"
else
from_email="${4}"
fi
mgUrlBase="https://api.mailgun.net/v3/${mg_domain}/messages"
## ${CURL} -s --user "api:${api_key}" \
#${CURL} --dump-header - --output - --user "api:${api_key}" \
# https://api.mailgun.net/v3/${mg_domain}/messages \
# -F from="${from_email}" \
# -F to="${to_email}" \
# -F subject="${subject}" \
# -F text="${text}"
# Build curlCMD
curlCMD="${CURL} -s --user \"api:${api_key}\""
#curlCMD="${CURL} --dump-header - --output - --user \"api:${api_key}\""
#echo "curlCMD=\"${curlCMD}\""
curlCMD="${curlCMD} ${mgUrlBase}"
#echo "curlCMD=\"${curlCMD}\""
echo "from_email=\"${from_email}\""
curlCMD="${curlCMD} -F from=\"${from_email}\""
#echo "curlCMD=\"${curlCMD}\""
# default separator is ','
to_sep=','
# support an additional separator '|'
additional_sep='|'
# Check if there is ${additional_sep} in ${to_email}
[[ "${to_email}" == *"${additional_sep}"* ]] && to_sep="${additional_sep}"
to_list="${to_email}"
to_prev=''
to_first=`echo "${to_list}" | cut -f 1 -d ${to_sep} | tr -d '\n'`
to_list=`echo "${to_list}" | cut -f 2- -d ${to_sep} | tr -d '\n'`
while [ "XX${to_first}" != "XX${to_prev}" ]; do
echo "to_first=\"${to_first}\"; to_prev=\"${to_prev}\""
curlCMD="${curlCMD} -F to=\"${to_first}\""
# echo "curlCMD=\"${curlCMD}\""
to_prev="${to_first}"
to_first=`echo "${to_list}" | cut -f 1 -d ${to_sep} | tr -d '\n'`
to_list=`echo "${to_list}" | cut -f 2- -d ${to_sep} | tr -d '\n'`
done
curlCMD="${curlCMD} -F subject=\"${subject}\""
#echo "curlCMD=\"${curlCMD}\""
curlCMD="${curlCMD} -F text=\"${text}\""
#echo "curlCMD=\"${curlCMD}\""
# Execute curlCMD
eval "${curlCMD}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment