2020年10月15日 星期四

Ubuntu 18.04 使用php ssmtp發送信件,以gamil為例

前置作業
- 確認環境的Port有開通,例如: 25、465、587是通的

安裝ssmtp 
sudo apt-get install ssmtp

設定sstmp config
sudo vi /etc/ssmtp/ssmtp.conf

修改如下設定
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
# 設定要用的轉寄信箱
root=[例:test@gmail.com]
# The place where the mail goes. The actual machine name is required no 
# MX records are consulted. Commonly mailhosts are named mail.domain.com
# 信箱SMTP位置
mailhub=[例:smtp.gmail.com:587]
#輸入以下登入驗證帳號/密碼
AuthUser=[例:sender@gmail.com]
AuthPass=[例:test@password]
#根據轉寄信規則選擇是否使用TLS、SSL
UseTLS=YES
UseSTARTTLS=NO
# Where will the mail seem to come from?
#輸入信箱網域名稱
rewriteDomain=[例:gmail.com]
# The full hostname
#主機名稱
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

新增php測試mail程式testmail.php
sudo vi /var/www/html/testmail.php

新增以下程式碼
<?php
$to="[例:test@mail.com]";
$subject="[例:這是主旨]";
$msg="[例:這是內文]";
$headers="From: [例:sender@gmail.com]";
if(mail("$to","$subject", "$msg", "$headers"))
        echo "send";
else
        echo "fail";
?>

測試
-到瀏覽器輸入[主機位置]/testmail.php,測試php程式;應該就會在php程式中to=的信箱收到信件

可查看寄送的mail log,判斷是否有問題;有可能因為驗證錯誤或網路問題而導致沒收到信
sudo tail /var/log/mail.log

(以上是在php7.2版本執行,不太確定是否其他版本還有其他需要的設定)

沒有留言:

張貼留言