首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHPMailer 群發 Gmail 常見問題彙總與解決方案

     編輯:PHP 相關知識

PHPMailer 群發 Gmail 常見問題彙總與解決方案

使用 PHPMailer 群發 Gmail 時常遇到各種問題,以下整理常見錯誤及解決方法。

1. Could not authenticate

若未使用迴圈,通常是帳號或密碼錯誤。若使用迴圈群發,send() 方法結束後務必呼叫 Smtpclose(),每發一封關一次連線,否則第二封會失敗。

2. Gmail SSL 設定

首先啟用 PHP 的 OpenSSL 擴充。

Windows 啟用方式:

  1. 檢查 php.ini 中 extension=php_openssl.dll 是否存在,移除前面的分號;若無則新增。
  2. 將 php_openssl.dll、ssleay32.dll、libeay32.dll 複製到 WINDOWS\system32\。
  3. 重啟 Apache 或 IIS。

Linux 啟用方式(以 PHP 5.2.14 為例):

# 下載原始碼
cd /var/www/php5
wget https://mirrors.sohu.com/php/php-5.2.14.tar.gz
tar zxvf php-5.2.14.tar.gz
cd php-5.2.14/ext/openssl/
/var/www/php5/bin/phpize
# 若找不到 config.m4,將 config0.m4 重命名
mv config0.m4 config.m4
/var/www/php5/bin/phpize
./configure --with-openssl --with-php-config=/var/www/php5/bin/php-config
make
make install
# 將產生的 openssl.so 複製到 extension_dir 目錄
# 編輯 php.ini 新增 extension=openssl.so
# 重啟 Apache
/usr/local/apache2/bin/apachectl restart

3. 修改 PHPMailer 以支援 SSL

Gmail 的 SMTP 和 POP3 皆採用 SSL 加密,需修改 class.phpmailer.php 和 class.smtp.php:

  1. 在兩個類別中新增屬性 public $Is_SSL = false;
  2. 在 PHPMailer 的 SmtpConnect 方法中傳遞:$this->smtp->Is_SSL = $this->Is_SSL;
  3. 在 SMTP 的 Connect 方法中 fsockopen 前加入:
    if($this->is_ssl){ $host = 'ssl://'.$host; }

使用範例

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Username = '***@gmail.com';
$mail->Password = '******';
$mail->From = '***';
$mail->FromName = '***';
$mail->CharSet = 'UTF-8';
$mail->Encoding = "base64";
$mail->IsHTML(true);
$mail->Subject = '***';
$mail->Body = '***';
$mail->AltBody = "text/html";
$mail->AddAddress('***', "");
$mail->Is_SSL = true;
$mail->Port = 587;
if (!$mail->Send()) { exit($mail->ErrorInfo); }
$mail->Smtpclose();
unset($mail);

完成上述三步驟,即可順利使用 PHPMailer 發送 Gmail。另附完整測試範例供參考。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved