Ubuntu 使用 ssmtp 透過 Gmail 發送 email

小蛙的主機會設定登入通知,如果有人登入系統,會自動寄送登入通知,如果接收到 email 通知,但卻不是小蛙自己登入的,就可能是被攻擊了 (哭哭),但是從不久前換了主機之後,這個功能失效了,但是另外一台原本的主機卻一直都是正常運作的,這篇記錄處理的過程。

小蛙透過 postfix 來寄送通知,但是從發現沒有收到 email 後,到 /var/log/mail.log 去看,出現了滿滿的錯誤訊息:

550-5.7.1 This message does not have authentication information or fails to pass 550-5.7.1 authentication checks. To best protect our users from spam, the 550-5.7.1 message has been blocked. Please visit 550-5.7.1 https://support.google.com/mail/answer/81126#authentication for more 550 5.7.1 information.

Google 了好一段時間,透過 CBL LOOKUP 可以查詢自己的 IP 有沒有被列入拒絕往來戶,小蛙看了半天,有些文章教人怎麼解除拒絕往來戶,有的教人怎麼加入 PTR 跟 Reverse DNS 來讓 Gmail 可以收到信,弄了一兩天,突然想到一個問題,嗯 ~ 既然小蛙的目的只是要寄信,主機的 IP 被 Google 拒絕,那 ~ 為什麼不直接用 Gmail 去寄信就好了。

安裝與設定 ssmtp

Google 查了一些文章發現有一套寄信軟體叫做 ssmtp,可以直接設定使用 Gmail 寄信,使用的指令方式也很簡單,於是照著 Sending email from Ubuntu server 16.04 via Gmail account 做,看英文不習慣的話,這邊有中文的「Linux 使用 SSMTP 與 GMail 以指令或程式自動寄信教學」,很快就可以安裝好了,下面大概記錄一下步驟:

sudo apt-get update
sudo apt-get install ssmtp
sudo vim /etc/ssmtp/ssmtp.conf
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
[email protected]
# 這邊填入寄送出 email 的人
# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com #mailhub=mail
mailhub=smtp.gmail.com:587
# 照著填
AuthUser=填入要用來寄信的 gmail
AuthPass=填入 gmail 密碼
UseTLS=YES
UseSTARTTLS=YES
# Where will the mail seem to come from?
#rewriteDomain=
rewriteDomain=gmail.com
# 照著填
# The full hostname
#hostname=localhost
hostname=填入你的主機名稱
# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
# 照著填

Gmail 二階段驗證(2FA)處理

如果有開啟二階段驗證( 2FA ),請參考「Linux 使用 SSMTP 與 GMail 以指令或程式自動寄信教學」。

測試發送信件

最後測試看看

echo "Hello ~" | sudo ssmtp -vvv [email protected]

這邊如果出現錯誤的話,要把 hostname 改成 localhost 再試一次就可以囉!

設定郵件內容

後來小蛙在 How to add subject line when sending email output of find using ssmtp 找到比較適合自己編輯內容的好方法,下面補上小蛙自己的發 email 的指令($IP, $HOSTNAME, $NOW 是小蛙自己用的變數,根據自己需要的內容修改掉即可),最後面用 printf 的原因是要換行,不然 echo 會把 \n 直接印出來。

{
echo To: 收件者 email
echo From: 寄件者 email
echo Subject: 主旨
printf "使用者資訊如下:\n\nIP:$IP\n登入到:$HOSTNAME\n登入時間:$NOW\n"
} | ssmtp 收件者 email

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *