mail命令入门及进阶

mail是linux shell中的邮件工具,与crontab配合使用,可以实现定期发送邮件。本文主要介绍mail工具使用方法及注意事项。

 

1、mail命令一般用法:

mail –s “邮件主题” –c”抄送地址” –b “密送地址” -f 发送人邮件地址 –F 发件人姓名 <要发送的邮件内容>

三种发信格式:

#第一种方法,把当前shell当成编辑器使用,编辑完内容后Ctrl-D结束

mail -s test [email protected]

#第二种方法,使用管道发送邮件

echo “mail content”|mail -s test [email protected]

#第三种方法,使用重定向,发送file内容

mail -s test [email protected]< file

 

2、发送html格式邮件:

要发送html格式的邮件,就需要指定html头。

方法1:在-s选项中增加html头“Content-Type:text/html”

echo "HTML Message goes here

" | mail-s "$(echo -e "This is the subject\nContent-Type:text/html")"  [email protected]

方法2:在-a选项中增加html头“Content-Type:text/html”

echo "HTML Message goes here

" | mail -a"Content-Type: text/html" -s "$(echo -e "This is the subject\n")"  [email protected]

 

3、与crontab配合使用:

需要注意mail和crontab配合使用时

1)注意crontab指令中%等特殊字符的处理,需要在前面加反斜杠\进行转义。

50 12 * * 5 echo "test" |mail -s "$(echo -e " Log `date+'\%Y\%m\%d'` \nContent-Type: text/html")" [email protected]

2)采用以上方法-e会被作为邮件标题发送,可使用mail的-a标签发送html的头信息。

5012  * * 5 echo "test"  |mail -a"Content-Type: text/html" -s "Statistic Log `date+'\%Y\%m\%d'`"  [email protected]

你可能感兴趣的:(Shell)