二十四、创建电子邮件脚本

主要使用Mailx程序实现

格式

mail [-eIinv] [-a header] [-b addr] [-c addr] [-s subj] to-addr

安装与卸载

#查询是否安装
[root@tzPC ~]# rpm -qa | grep mailx
#卸载
[root@tzPC ~]# yum -y remove sedmail postfix
#安装
[root@tzPC ~]# yum -y install mailx postfix

启动服务

[root@tzPC 25Unit]# systemctl start postfix
#默认安装完后服务是stop的,使用mailx发送邮件发送不出去
[root@tzPC 25Unit]# systemctl enable postfix
#添加到开机启动项

查询是否25端口监听127.0.0.1

注意如果未发现25端口那可能为服务未启动

[root@tzPC 25Unit]# ss -tnl
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      50              *:139                         *:*                  
LISTEN      0      128             *:111                         *:*                  
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      100     127.0.0.1:25                          *:*                  
LISTEN      0      50              *:445                         *:*

Mailx命令行参数

参数 描述 参数 描述
-a 指定SMTP头部行 -i 忽略TTY中断信号
-b 指定密送人 -I 强制mailx以交互模式运行
-c 指定抄送人 -n 禁止读取/etc/mail.rc文件
-r 指定发件人 -s 指定一个主题行
-e 如果消息为空则不发送 -v 显示投递细节

在命令行上发送邮件消息

[root@tzPC 25Unit]# echo "This is a test message " | mailx -s "Test message" root

脚本如下

[root@tzPC 25Unit]# cat diskmail.sh 
#!/bin/bash
#sending the current disk statistics in an e-mail message
date=$(date +%m/%d/%Y)
MAIL=$(which mailx)
TEMP=$(mktemp tmp.XXXXXX)
df -kh >$TEMP
cat $TEMP | $MAIL -s "Disk stats for $date" $1
rm -f $TEMP

效果

[root@tzPC 25Unit]#mail root

 

 学习来自:《Linux命令行与Shell脚本大全 第3版》第25章

posted @ 2020-09-09 16:43  努力吧阿团  阅读(238)  评论(0编辑  收藏  举报