使用ncat / netcat / telnet发送多个base64电子邮件附件

时间:2016-06-27 23:08:58

标签: bash email telnet netcat

我正在寻找使用bashncat的解决方案。在this question on ServerFault工作之后,我已经重新设计了它,mostly this answer,非常基本;允许使用ncat代替netcat来包含CC收件人,并清理它以供我使用(简单的东西)。如下所示:

# Email Recipient
TOEMAIL="$REPORTRCPT";
# Default Subject
SUBJECT="Build report for $MACHINEFQDN - $DATE @ $DATETIME (PST)";
# Default Contents
MSGBODY="See attachment. Includes all output as seen while running the script.";
# Default Attachment
ATTACHMENT="/tmp/$MACHINENAME-build-$DATE.html"
ATTACHMENT2="/tmp/40_custom-$MACHINENAME-$DATE"
# Default smtp server
mailserver="111.111.111.112"
mailserverPort="25"

fappend() {
    echo "$2">>$1;
}

domain=`grep search /etc/resolv.conf | awk '{print $2;}'`
computer=`hostname`
user=`whoami`
FREMAIL="$user@$computer.$domain"

MIMETYPE=`file --mime-type -b $ATTACHMENT`
MIMETYPE2=`file --mime-type -b $ATTACHMENT2`
TMP="/tmp/tmpmail_"`date +%N`;
BOUNDARY=`date +%s|md5sum|awk '{print $1;}'`
FILENAME=`basename $ATTACHMENT`
FILENAME2=`basename $ATTACHMENT2`

DATA=`cat $ATTACHMENT|base64`
DATA2=`cat $ATTACHMENT2|base64`

rm $TMP 2> /dev/null

fappend $TMP "EHLO $computer.$domain"
fappend $TMP "MAIL FROM:<$FREMAIL>"
fappend $TMP "RCPT TO:<$TOEMAIL>"
fappend $TMP "RCPT TO:<$REPORTRCPTCC>"
fappend $TMP "DATA"
fappend $TMP "From: $FREMAIL"
fappend $TMP "To: $TOEMAIL"
fappend $TMP "Cc: $REPORTRCPTCC"
fappend $TMP "Reply-To: $FREMAIL"
fappend $TMP "Subject: $SUBJECT"
fappend $TMP "Content-Type: multipart/mixed; boundary=\"$BOUNDARY\""
fappend $TMP ""
fappend $TMP "This is a MIME formatted message.  If you see this text it means that your"
fappend $TMP "email software does not support MIME formatted messages."
fappend $TMP ""
fappend $TMP "--$BOUNDARY"
fappend $TMP "Content-Type: text/plain; charset=UTF-8; format=flowed"
fappend $TMP "Content-Disposition: inline"
fappend $TMP ""
fappend $TMP "$MSGBODY"
fappend $TMP ""
fappend $TMP ""
fappend $TMP "--$BOUNDARY"
fappend $TMP "Content-Type: $MIMETYPE; name=\"$FILENAME\""
fappend $TMP "Content-Transfer-Encoding: base64"
fappend $TMP "Content-Disposition: attachment; filename=\"$FILENAME\";"
fappend $TMP ""
fappend $TMP "$DATA"
fappend $TMP ""
fappend $TMP ""
fappend $TMP "--$BOUNDARY--"
fappend $TMP ""
fappend $TMP "."
fappend $TMP "quit"

ncat $mailserver $mailserverPort < $TMP >> $TMP
rc="$?"
if [ "$rc" -ne "0" ]; then
    echo "Returncode: $rc"
    echo "Please inspect $TMP"
else
    echosuccess "Email successfully sent, you should receive it!"
    rm $TMP;
fi

但是,我一直在努力寻找它的是多个base64附件。我已经尝试过各种各样的事物,BOUNDARY等等,如上所示,添加其他变量。但我空洞了。有谁熟悉并能够伸出援助之手?我希望它能像添加CC收件人一样容易和直接。

1 个答案:

答案 0 :(得分:0)

原则上,您的脚本适合我(经过一些调整,例如将ncat替换为telnet)。你应该遵循它的建议和“请检查$ TMP”。但是您不应该使用< $TMP >> $TMP将诊断输出附加到输入;更好地使用单独的日志输出文件。另外,方法

DATA=`cat $ATTACHMENT|base64`

只有编码附件对于命令行来说不会太长时才起作用。你可以替换

fappend $TMP "$DATA"

base64 $ATTACHMENT >>$TMP

克服这个门槛。