Linux|系统管理|WEB开发

关注Linux,系统管理,WEB开发以及开源世界

命令行发送html邮件和带附件的邮件

| Comments

在命令行发送带附件的邮件倒是很早就知道了,我的方法是采取最懒的,用mutt来把帮忙。命令很简单 echo "your email body" | mutt -s "here you subject" -a /path/to/mutt.tar.gz your@email.com 当然如果你的邮件正文很长,那就可以采用重定向的方式了。

mutt -s "here you subject" -a /path/to/mutt.tar.gz your@email.com 但是这种方式发送html格式正文的邮件却不成功,因为邮件头默认是text/plain格式的,不是text/html格式。 网上有人说可以配置~/.muttrc来解决这个问题,但是我看了muttrc的man手册,也尝试了一下,但是没有结果。

今天尝试用sendmail命令,而不是以前用的mail命令来发html格式邮件,经过测试,已经成功了。其实很简单,就是在邮件头上指定邮件格式。这种方式也可以发送附件,不过显然不如mutt -a来得简单方便还准确。

下面是发送html邮件的代码

#!/bin/bash
#send a html-email using sendmail command
#author:mlsx mlsx(dot)xplore(at)gmail(dot)com
#license:GPL

from=”my@mydomain.com”
subject=”test html-email using mail command”
msgdate=`date +”%a, %e %Y %T %z”` # Leave alone
emailtarget=”your@yourdomain.com”

daemail=$(cat < Date: $msgdate
From: $from
To:$emailtarget
Subject: $subject
Mime-Version: 1.0
Content-Type: text/html; charset=gb2312
!)

echo "$daemail" > msg.tmp
echo >>msg.tmp
cat test.html >>msg.tmp
echo >> msg.tmp
cat msg.tmp |sendmail -t
rm -f msg.tmp

这里把邮件正文内容保存到了test.html文件里。下次发送邮件时之需要修改test.html就好了。

当然这个脚本还可以做很多修改,比如发送地址从命令行或者文件读取等,这里就不再扩展了。因为我要说的发送html邮件已经成功了。

Comments