使用 PHPMailer 群發 Gmail 時常遇到各種問題,以下整理常見錯誤及解決方法。
若未使用迴圈,通常是帳號或密碼錯誤。若使用迴圈群發,send() 方法結束後務必呼叫 Smtpclose(),每發一封關一次連線,否則第二封會失敗。
首先啟用 PHP 的 OpenSSL 擴充。
php.ini 中 extension=php_openssl.dll 是否存在,移除前面的分號;若無則新增。php_openssl.dll、ssleay32.dll、libeay32.dll 複製到 WINDOWS\system32\。# 下載原始碼 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
Gmail 的 SMTP 和 POP3 皆採用 SSL 加密,需修改 class.phpmailer.php 和 class.smtp.php:
public $Is_SSL = false;SmtpConnect 方法中傳遞:$this->smtp->Is_SSL = $this->Is_SSL;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。另附完整測試範例供參考。