前言
想定期查詢天氣並提示我,很容易想到了創建定時任務然后給我自己發郵件,進而學習了linux如何發郵件,下面就開始吧。
開啟郵件服務(Ubuntu)
- 首先執行
mail
命令看有沒有安裝,沒有的話會提示安裝mailutils,執行sudo apt install mailutils
安裝,默認安裝所有就好。 - 此時已經安裝好了mail,mailx服務程序,還有postfix郵件服務器,而sendmail郵件服務器已經過時,默認沒有安裝,如果安裝了請卸載sendmail服務器。
- 配置mail,使用smtp功能。
vim /etc/mail.rc
打開或者創建文件並填寫以下內容:
其中,password是使用163郵箱生成的授權碼,不是郵箱密碼(163郵箱要開啟smtp服務哦).set from=crab@163.com set smtp=smtp.163.com set smtp-auth-user=crab@163.com set smtp-auth-password=****** set smtp-auth=login
- 查看postfix狀態,需要開啟此服務
sudo service postfix status
sudo service postfix start
ok,到這里已經可以發送郵件啦! - 發送郵件測試一下
echo today is a nice day! | mail -s today crab@163.com
等一會就收到郵件了,我試了qq郵箱也是可以的,而outlook郵箱把郵件拉進了反垃圾黑名單,被退回來了:😢:,暫時沒找到解決辦法。
實現定時任務
- 編寫腳本
vim /home/popo/getweather.sh
curl -H "Accept-Language:zh" wttr.in/paris > /home/popo/today.weather
,查詢天氣信息並寫入文件
chmod a+x /home/popo/getweather.sh
,修改可執行權限
cd /home/popo
,嘗試執行./getweather.sh
,查看天氣cat today.weather
vim /home/popo/send.sh
echo Weather information has arrived.|mail -s "weather" crab@163.com < today.weather
發送天氣郵件
chmod a+x send.sh
,修改可執行權限
嘗試執行./send.sh
,查看郵件是否收到 - 創建任務
crontab -l
,查看當前任務列表
crontab -e
,編寫任務
在末尾添加0 12 * * * /bin/bash /home/popo/getweather.sh
和0 13 * * * /bin/bash /home/popo/send.sh
表示在每天中午十二點查詢天氣,十三點發送郵件。ok,大功告成!