哎,今天一直在找怎么发送带附件的有是html格式的邮件.如果只是html格式或者只是带附件的都好弄,但是这两个都要弄的话还是很费时间.但是,终于在一篇好帖的帮助下弄出来了.
http://www.zedwood.com/article/bash-send-mail-with-an-attachment帖子只把做法贴出来了,里面有的评论对做法做了大致的讲解.当然了,不仅仅支持html和excel,还支持发送图片等等文件,应该是只要MIME有的文件都支持。
#!/bin/bash
#requires: basename,date,md5sum,sed,sendmail,uuencode
function fappend {
echo "$2">>$1;
}
YYYYMMDD=`date +%Y%m%d`
# CHANGE THESE
TOEMAIL="recipient@email.com";
FREMAIL="crondaemon@65.244.254.144";
SUBJECT="Daily Backup - $YYYYMMDD";
MSGBODY="Hello this is the message body";
ATTACHMENT="/home/joeuser/Untitled.png"
MIMETYPE="image/png" #if not sure, use http://www.webmaster-toolkit.com/mime-types.shtml
# DON'T CHANGE ANYTHING BELOW
TMP="/tmp/tmpfil_123"$RANDOM;
BOUNDARY=`date +%s|md5sum`
BOUNDARY=${BOUNDARY:0:32}
FILENAME=`basename $ATTACHMENT`
rm -rf $TMP;
#可能有的机器没有uuencode,但是服务器一般支持下载sudo yum install sharutils
cat $ATTACHMENT|uuencode --base64 $FILENAME>$TMP;
sed -i -e '1,1d' -e '$d' $TMP;#removes first & last lines from $TMP
DATA=`cat $TMP`
rm -rf $TMP;
fappend $TMP "From: $FREMAIL";
fappend $TMP "To: $TOEMAIL";
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";
#这个是发送html正文
fappend $TMP "Content-Type: text/html; charset=utf-8;format=flowed"
fappend $TMP "Content-Transfer-Encoding: 7bit";
fappend $TMP "Content-Disposition: inline";
fappend $TMP "";
fappend $TMP "$htmlcontent";
fappend $TMP "";
fappend $TMP "";
fappend $TMP "--$BOUNDARY";
#这个是发送excel附件
fappend $TMP "Content-Type: application/vnd.ms-excel; 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 "Content-Type: application/vnd.ms-excel; 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 "";
#cat $TMP>out.txt
cat $TMP|sendmail -t;
rm $TMP;