天天看點

使用Linux的mail指令發郵件

日常運維經常需要系統告警、平台巡檢情況定時發送到郵箱,在Linux中設定好配置檔案,一個指令就可以搞定,分三步設定(注意郵件服務的端口是否開放,詳見第五步):

1、開啟郵箱POP3/SMTP/IMAP服務,設定郵箱授權碼

使用Linux的mail指令發郵件

2、修改/etc/mail.rc,在檔案末尾增加以下内容,指定外部的smtp伺服器位址、帳号密碼等:

$ vi /etc/mail.rc  
set [email protected]
set smtp=smtp.yeah.net  
set smtp-auth-user=123456
set smtp-auth-password=admin
set smtp-auth=login  
#from是你設定stmp服務的郵箱位址,也就是用來發送郵件的郵箱位址
#smtp是發生的外部smtp伺服器的位址,看你用的什麼郵箱了,在設定裡面可以看到
#smtp-auth-user是外部smtp伺服器認證的使用者名
#smtp-auth-password是外部smtp伺服器認證的使用者密碼(授權碼)
#smtp-auth是郵件認證的方式           

複制

3、用mail指令發送郵件

echo 'hello world' | mail -s 'hi' [email protected]           

複制

4、拓展内容--mail指令詳解

#四種常用格式發信:#第一種方法,你可以把目前shell當成編輯器來用,編輯完内容後Ctrl-D結束
mail -s test [email protected] 
#第二種方法,我用的最多,可能是喜歡管道的緣故吧
echo “mail content”|mail -s test [email protected] 
#第三種方法,以file的内容為郵件内.容發信
mail -s test [email protected]< file 
#第四種方法,給多個使用者發送郵件
mail -s test -c [email protected]  [email protected]< file           

複制

5、mail服務需要開的端口

注意:阿裡雲等雲服務商預設是封了的25端口的,(發郵件的SMTP的協定預設是25端口),需要把端口号改成465端口,然後給它一個ssl證書。

--參考文章:阿裡雲伺服器發送郵件 - 野豬喬治 - 部落格園 (cnblogs.com)

第一步:安裝mailx郵箱服務

yum -y install mailx           

複制

第二步:在mailx配置檔案裡添加使用者名,密碼。mailx的配置檔案是/etc/mail.rc這個檔案。

set ssl-verify=ignore              ###   啟用證書
set nss-config-dir=/root/.certs    ###   證書存放的位置
set from="[email protected]"    ###   郵箱
set smtp="smtps://smtp.yeah.net:465"      ###   郵箱伺服器位址
set [email protected]  ###   郵箱
set smtp-auth-password=admin        ###   郵箱授權碼(不是郵箱登入密碼,不知道的話自己上去開通)
set smpt-auth=login                 ###   啟用自動連接配接登入,就是發送郵件的時候自動連接配接到163伺服器幫你發送郵件           

複制

第三步:既然要用到證書,那我們還得在163的伺服器上申請一個證書,證書名字自己定義,我這裡指令為yeah.crt。

mkdir -p /root/.certs    ###    證書存放位置
cd  /root/.certs
###下面這幾條指令每一條我也不是太明白,我隻知道生成了證書和證書檔案,和啟用的證書!echo -n |openssl s_client -connect smtp.yeah.net:465 |sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' >yeah.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/yeah.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/yeah.crt
certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ~/.certs/./ -i yeah.crt
certutil -L -d /root/.certs           

複制

使用Linux的mail指令發郵件

然後就可以發送郵件了。