如何解决Debian环境下PHPMailer无法发送测试邮件的问题?
PHPMailer无法发送邮件排查求助
我在Debian/Bullseye系统上运行本地Apache2服务器,尝试用PHPMailer发送测试邮件始终失败,情况如下:
- PHP环境正常,原有PHP脚本可正常运行
- 两种安装方式均无效果:
- Composer安装:生成带autoload.php的vendor目录,但测试脚本test.php无法运行
- GitHub下载压缩包手动解压到网站根目录:mailer.php运行后仅显示空白页面,既无发送成功提示,也无拒绝反馈
- SMTP配置已替换为托管服务商提供的真实信息(发件邮箱、登录密码、SMTP服务器地址、安全设置及端口),TLS配置来自服务商,确认正确
以下是使用的mailer.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\SMTP; use PHPMailer\PHPMailer\Exception; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; //Create an instance; passing `true` enables exceptions $mail = new PHPMailer(true); Try { //Server settings $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output $mail->isSMTP(); //Send using SMTP $mail->Host = 'mail.<domain>.ca'; //Set the SMTP server to send through $mail->SMTPAuth = true; //Enable SMTP authentication $mail->Username = 'mail@<domain>.ca'; //SMTP username $mail->Password = '<secret>'; //SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption $mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` //Recipients $mail->setFrom('mail@<domain>.ca', ‘from me’); $mail->addAddress('gary@<domain>.ca', ‘to me’); //Add a recipient // $mail->addAddress('Recipient@emailaddress.com'); //Name is optional // $mail->addReplyTo('yourname@domain.com', ‘Your Name’); // $mail->addCC('cc@example.com'); // $mail->addBCC('bcc@example.com'); //Attachments Optional // $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments // $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name //Content $mail->isHTML(true); //Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body in bold!'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } ?>
排查建议
开启PHP错误显示:空白页面大概率是PHP报错未输出,在脚本开头添加以下代码,或修改php.ini开启
display_errors = On后重启Apache:ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);检查文件路径:
- Composer安装时,确认
require 'vendor/autoload.php';的路径与test.php的相对位置正确 - 手动安装时,确认
require 'PHPMailer/src/...'的路径正确,若PHPMailer未放在网站根目录,需调整相对路径
- Composer安装时,确认
修正字符编码问题:脚本中使用了中文全角引号(如
‘from me’),替换为英文半角引号'from me',避免语法错误测试SMTP连接:
- 用
telnet mail.<domain>.ca 465测试本地服务器能否连接SMTP端口,若失败,排查本地iptables或服务商防火墙是否拦截465端口 - 尝试切换加密方式:将
SMTPSecure改为PHPMailer::ENCRYPTION_STARTTLS,端口改为587后重新测试
- 用
查看Apache错误日志:日志路径通常为
/var/log/apache2/error.log,从中查找PHP报错信息,定位具体问题
内容的提问来源于stack exchange,提问作者Gary Dale
相关产品推荐
相关产品推荐

