2021年4月7日

XAMPP 實作Google郵件伺服器發送E-mail (Apache Web Server + Mail Server, PHP)

最近在玩Arduino,剛好有個需求需要透過Arduino的WiFi模組傳資料到WebServer,再透過Mail Server發送郵件通知。


XAMPP安裝過程網上有很多可參考,我就略過不談,直接從Mail Server開始吧。

一、設定php.ini

開啟C:\xampp\php資料夾底下的php.ini


開啟文件後,按CTRL+F搜尋"mail function"

將以下對應的關鍵字替換成以下內容

port設定465是因為我有開啟SSL加密,否則一般設定587即可。


  1. SMTP=smtp.gmail.com
  2. smtp_port=465
  3. sendmail_from = 你的帳號@gmail.com
  4. sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

二、設定sendmail.ini

開啟C:\xampp\sendmail資料夾底下的sendmail.ini


文件開啟後,直接按CTRL+F搜尋"sendmail"。

找到以下內容做修改。

  1. smtp_server=smtp.gmail.com
  2. smtp_port=465
  3. error_logfile=error.log
  4. debug_logfile=debug.log
  5. auth_username=Google帳號@gmail.com
  6. auth_password=密碼
  7. force_sender=Google帳號@gmail.com

三、建立發送郵件程式sendmail.php

在C:\xampp\htdocs資料夾底下新增sendmail.php

程式片段如下

  1. <?php
  2. $to_email = "收件者帳號@gmail.com";
  3. $subject = "火災警報通知";
  4. $body = "您的Arduino煙霧感測器MQ-7已偵測到一氧化碳濃度過高。";
  5. $headers = "From: Arduino's MQ-7";
  6.  
  7. if (mail($to_email, $subject, $body, $headers))
  8. {
  9. echo "Email successfully sent to $to_email...";
  10. }
  11. else
  12. {
  13. echo "Email sending failed...";
  14. }
  15. ?>

四、啟動/重啟 Apache Server


五、透過瀏覽器執行發送郵件的PHP程式

開啟瀏覽器,網址列打上127.0.0.1/sendmail.php,按下Enter等待程式執行結束,結果如下圖。


六、Google帳號安全性設定

基本上,前幾項設定完就可以發送郵件了,但我在發送時總出現這個訊息【Username and Password not accepted.】,爬文後才發現使用Google帳號發送郵件,會被Google安全性設置擋在門外,不給授權的情況。

若你也有這樣的情況,請到以下頁面將低安全性應用程式存取權打開。



若上方設定開啟,還是無法授權登入,再進到下方鏈結授權存取您的 Google 帳戶




參考資料

沒有留言:

張貼留言