这几天在排查线上环境问题时,经常遇到想从服务器取东西的情况,或是sql脚本或是日志,因为不能用winscp直链服务器,同时linux中也没有什么可用来全选文本的快捷键,所以考虑用邮件的方式将需要的文件转发出来。开始想尝试使用sendmail之类的自带工具,但发现其配置过程并不简单,于是想到用telnet工具开发一个简单的发邮件脚本,使用这个脚本不但配置简单,而且可以零修改移植。在脚本中,只要配置smtp服务器域名,该smtp邮箱服务器的账号、密码,以及收件人列表即可。
需要注意的是,使用该脚本需要首先安装telnet工具,同时保证服务器可以访问smtp服务器(例如,可用telnet smtp.163.com 25验证)。
仅验证了附件为几百k的文本情况下功能,当发送非文本,或大文件时尚不能保证结果。同时该脚本只有发送功能,目前还不具备收取邮件的功能。
附上shell脚本源码:
---------------------------
#!/bin/bash
#Created 2016-05-06 by layido#VERSION 1.0
#telnet smtp to send email with attachment
#USAGE:./sendemail.sh [attachment]
SMTPSERVER="smtp.163.com"
SMTPUSER="account@163.com"
USER=`echo -n $SMTPUSER|base64`
PWD=`echo -n "password"|base64`
RCPT="recver1@qq.com recver2@139.com"
Recvlist=(${Recvlist[*]} $RCPT)
subjectName="email through telnet"
mailContext="edit your mail context"
function maild {
(for a in "helo localhost" "AUTH LOGIN" "$USER" "$PWD" "mail FROM:<$SMTPUSER>"; do
sleep 1
echo $a
sleep 1
done
for b in ${Recvlist[*]}
do
echo "rcpt TO:<$Recvlist>"
sleep 1
done
echo "data"
sleep 1
echo "from:<$SMTPUSER>"
echo "to:${Recvlist[*]}"
echo "subject:$subjectName"
echo "Content-type: multipart/mixed; boundary=\"#BOUNDARY#\""
echo ""
echo "--#BOUNDARY#"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Transfer-Encoding: quoted-printable"
echo ""
echo "$mailContext"
echo "--#BOUNDARY#"
echo "Content-Type: application/octet-stream;name=\"$filename\""
echo "Content-Transfer-Encoding: base64"
echo ""
echo "$fileContent"
echo "--#BOUNDARY#--"
echo "."
sleep 1
echo "QUIT")|telnet $SMTPSERVER 25
}
if [ $# -gt 1 ]
then
echo "Usage:$0 [attachment]"
exit
fi
if [ $# -eq 0 ]
then
echo "send email with script as attachment"
filename=`basename $0`
fileContent=`cat $0|base64`
maild
else
filename=`basename $1`
if [ ! -e $filename ]
then
echo "$filename not exists"
exit
else
fileContent=`cat $1 |base64`
echo $fileContent
maild
fi
fi