首页 > 解决方案 > PHPMailer cli 可以,cgi 不行,为什么?

问题描述

我有两台机器安装了最新的 Ubuntu 16.04、php 7 和 PHPMailer。电子邮件通过 gmail 使用 ssmtp 及其关联的 sendmail 存根发送。如果我从命令行和 cgi (Apache2) 运行相同的程序(实际上是 Wiki 中教程中的代码),则命令行可以工作,而 cgi 不能,并给出错误消息“邮件程序错误:无法实例化邮件功能。”

请不要说阅读我拥有的故障排除指南,我很抱歉,但一个小小的批评有点神秘,我不明白。(我们都在努力保持简短和简单。)

但是,如果我检查 php.ini 文件,它们在影响电子邮件的区域是相同的。

有没有我错过的必要差异?怎么了?

<?php

require_once('phpmailer.php');
require_once('exception.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$bodytext = "This is a test EMail sent from the sever.    

Frank\n";

$email = new PHPMailer();
$email->From      = 'reception@xxx.xxx.uk';
$email->FromName  = 'Frank';
$email->Subject   = 'Test Email';
$email->Body      = $bodytext;
$email->AddAddress( 'frank@xxxx.xxx.uk' );

return $email->Send();

echo "Done";

?>

我知道它对于 cgi 来说是垃圾,但关键是它应该在两者中运行。

mail.err 日志显示

Apr 30 10:14:02 Desktop-Frank sSMTP[5579]: Unable to connect to "smtp.gmail.com" port 597.
Apr 30 10:14:02 Desktop-Frank sSMTP[5579]: Cannot open smtp.gmail.com:597

这与前端错误消息相关。

我的猜测是两种方法之间缺少一条信息或有所不同。从 ssmtp 返回的错误信息被误解了。

我什至尝试更新 php.ini 以提供 sendmail 二进制存根的完全解析路径。

有人可以帮我解决这个问题吗?

谢谢弗兰克

更新:两种环境中的工作代码

我仍然不明白为什么原始代码在 cgi 环境中不起作用,但好消息是以下在 cgi 和 cli 中都有效!

记得将 phpmailer.php、exception.php 和 smtp.php 放入 /usr/share/php/ 并观察文件名。

<?php

require_once('phpmailer.php');
require_once('exception.php');
require_once('smtp.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

$bodytext = "This is a test EMail sent from the sever.";

$email = new PHPMailer();
$email->From      = 'xxx@xxx.xx.xx'; # replaced by google with Username
$email->FromName  = 'Appears in From ahead of your gmail address';
$email->Sender    = 'xxx@xxx.xx.xx'; # not visible to recipient
$email->Subject   = 'Appears in the subject field';
$email->Body      = $bodytext;
$email->AddAddress( 'xxx@xxxx.xx.xx' );
$email->AddAttachment( '/fullpath/file.name' );
$email->isSMTP();
$email->SMTPAuth = true;
$email->SMTPDebug = 4; # lots of debug 0 for production
$email->SMTPSecure = 'tls';
$email->Port = 587;
$email->Username = 'gmail email address';
$email->Password = 'gmail password';
$email->Host = 'smtp.gmail.com';

echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Value</td></tr>\n";
foreach($email as $key=>$item) {
    echo "<tr><td>".$key."</td><td>".$item."</td></tr>\n";
}
echo "</table>";

return $email->Send();

echo "Done";

?>

感谢大家,特别是 Synchro 的耐心。

坦率

标签: phpapache2cgiphpmailerssmtp

解决方案


启用SMTP安全选项并将端口更改为 465。

$mail->SMTPSecure = 'ssl'; 
$mail->Port       =  465;                    // set the SMTP port

设置 SMTP 邮件密码

$mail->Password   = "mailpassword";  // SMTP password

推荐阅读