在上一篇 [PHP] 使用PHPMailer線上發信通過驗證的SMTP 中我們討論到如何使用 PHPMailer 類別來通過 SMTP 驗證的伺服器,其實如果您下載了 PHPMailer 並解開壓縮後,可以在<examples>資料夾中看到各個不同狀況下使用 PHPMailer 來發信的程式碼,其中<test_gmail.php>就是使用 PHPMailer透過Gmail的範例。
使用前注意事項
- 使用PHPmailer時,PHP 必須安裝 OpenSSL 的擴充程式。 最好使用php 5以上,因為php 4 ,有OpenSSL的bug…,然後phpmailer 使用2.1 以上版本for php 5/6。關於openssl的安裝方式可以參考一下這篇文章 「php安裝openssl的方法 」。
- 使用 PHPMailer 透過 Gmail 帳號寄信時,需要採用安全性較低的登入技術,所以要開啟安全性較低的應用程式存取權限,您可以在登入 Gmail 帳號後由https://www.google.com/settings/security/lesssecureapps 開啟,否則會造成「send-mail: Authorization failed 534 5.7.14」認證錯誤。
- 開發測試時建議您可以開啟 PHPMailer 的 Debug 模式,可以很清楚知道運作的過程,若發生錯誤也可以很快得知問題所在,其語法如下:
//Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 2;
PHPMailer 範例程式(SSL)
<?php
include("PHPMailerAutoload.php"); //匯入PHPMailer類別
$mail= new PHPMailer(); //建立新物件
$mail->IsSMTP(); //設定使用SMTP方式寄信
$mail->SMTPAuth = true; //設定SMTP需要驗證
$mail->SMTPSecure = "ssl"; // Gmail的SMTP主機需要使用SSL連線
$mail->Host = "smtp.gmail.com"; //Gamil的SMTP主機
$mail->Port = 465; //Gamil的SMTP主機的SMTP埠位為465埠。
$mail->CharSet = "big5"; //設定郵件編碼
$mail->Username = "*********"; //設定驗證帳號
$mail->Password = "*********"; //設定驗證密碼
$mail->From = XXX@XXX.XXX.XXX; //設定寄件者信箱
$mail->FromName = "測試人員"; //設定寄件者姓名
$mail->Subject = "PHPMailer 測試信件"; //設定郵件標題
$mail->Body = "大家好,
這是一封測試信件!
"; //設定郵件內容
$mail->IsHTML(true); //設定郵件內容為HTML
$mail->AddAddress("david@e-happy.com.tw", "茶米"); //設定收件者郵件及名稱
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>