通常在租用主機環境,都會處理好mail server所需的相關設定,
如果在開發過程中,可以在local端就能測試寄發email效果,對開發者而言,一定會更加方便
因此,本文主要說明在 windows 本地 localhost( 127.0.0.1)
如何使用 phpmailer 來透過 GMAIL SMTP server 寄信
![How to using phpmailer to sending gmail smtp e-mail in windows localhost How to using phpmailer to sending gmail smtp e-mail in windows localhost](https://s-media-cache-ak0.pinimg.com/originals/3e/0f/c2/3e0fc2078baeaf5abddc6643b6a7a672.png)
(一) 開啟 windows openssl 教學
在windows local端要透過Gmail SMTP發信前,要先開啟openssl
首先,先開啟Appache的openssl功能
1. 先在 php 資料夾內複製這兩個檔案 libeay32.dll、ssleay32.dll 並且在 windows/system32/ 貼上這兩個檔案
2. 接著,修改php.ini 找到以下兩行,去除前面分號 並且將smtp_port改成465
extension=php_openssl.dll
...
smtp_port = 465
3. 重新啟動webserver 重新啟動webserver(apache or nginx)後 查看 phpinfo.php 搜尋 OpenSSL support ,確認狀態為 enabled 則表示已經設定完成
(二) 下載 phpmailer
前往phpmailer github頁面 建議使用 composer 來安裝 [教學] 下載完畢後,載入phpmailer並且調整gmail smpt相關參數 Host設定為 “smtp.gmail.com” SMTPSecure 設定為安全資料傳輸層 (SSL) Port 設定為安全資料傳輸層通訊埠:465 並且填寫你的完整電子郵件地址及Gmail 密碼
另外,建議可以將 SMTP Debug 設定為 2,方便debug
send.php
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true);// Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'YOURUSER@gmail.com'; // SMTP username
$mail->Password = 'GMAIL_PASSWORD'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('sendfrom@gmail.com', 'Shop admin');
$mail->addAddress('sendto@gmail.com', 'Username'); // Add a recipient
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
(三) 開啟google 的低安全性應用程式存取權限
前往: https://www.google.com/settings/security/lesssecureapps
將安全性較低的應用程式存取權限 “開啟”
(注意! 已啟用兩步驟驗證功能的帳戶無法使用這項設定。)
否則會發生 534 5.7.14 、 Message could not be sent.Mailer Error: SMTP connect() failed. 的錯誤 詳情可以參考 無法登入電子郵件程式 疑難排解