Linux邮件发送

简介

最近在折腾Linux,想做一点有趣的事情,首先想到就是通过定时任务,做一些通知,原来我就做过Java整合邮件,做一些邮件发送,直到最近我才知道,原来Linux本身就能发送邮件的。

那更好了,直接开始。

参考:

  • https://linux.cn/article-11663-1.html

  • https://www.jianshu.com/p/d1f757c89826

开始

如果你懒得打开上面的两个链接,那我解释一下,第一个是Linux发送邮件的几种方式,第二个是使用ssl发送邮件的配置方式。

安装mailx

1
yum install mailx

编辑配置

1
vim /etc/mail.rc

最后添加

1
2
3
4
5
6
7
8
9
10
11
12
13
# 发出邮件地址
set from=example@qq.com
# smtp配置,与上面对应
# 通常不使用ssl,smtp使用25端口,配置采用下面的即可
# 使用ssl,smtp使用465端口,配置要改为 stmps://smtp.qq.com
set smtp=smtp.qq.com
set smtp-auth-user=example@qq.com
set smtp-auth-password=**************
set smtp-auth=login

# 如果要用ssl就要加上下面的
set ssl-verify=ignore
set nss-config-dir=/root/.certs

证书配置

使用ssl,必须要配置证书

1
2
3
4
5
6
mkdir -p /root/.certs/
echo -n | openssl s_client -connect smtp.qq.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/qq.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ~/.certs/./ -i qq.crt
certutil -L -d /root/.certs

测试

1
echo "This is the mail body" | mail -a /home/wnh/apps/spring/application.properties -s "Subject" wnhyang@139.com

补上

要定时的脚本

1
2
3
4
5
6
7
8
info="This is the mail body\n磁盘使用情况:\n`df -h`\n内存使用情况:\n`free -h`进程运行情况:\n`top -n 1`"

zip -r /home/wnh/linux_bak.zip /home/wnh/script /home/wnh/mail /home/wnh/apps

curl -i -k -H "Content-type: application/json" -X POST -d '{"mailbox": "wnhyang@139.com","subject": "testMail","content": "${info}"}' http://127.0.0.1:8093/email/4

echo -e "${info}" | mail -a /home/wnh/linux_bak.zip -s "Subject" wnhyang@139.com

定时执行

1
2
3
4
5
6
7
8
9
10
# 查看定时任务
crontab -l

# 编辑定时任务
crontab -e

# 移除定时任务
crontab -r

00 12 * * 5 /home/wnh/script/mail.sh