天天看點

使用telnet發送附件郵件

        這幾天在排查線上環境問題時,經常遇到想從伺服器取東西的情況,或是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="[email protected]"

USER=`echo -n $SMTPUSER|base64`

PWD=`echo -n "password"|base64`

RCPT="[email protected] [email protected]"

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