PHP SMTP Office 365 - 发送附件

PHP SMTP Office 365 - Send attachment

我正在使用 Office 365 身份验证发送 PHPMailer 电子邮件。

这工作正常。但是我正在努力让脚本发送附件。

这是我的代码

require_once('phpMailer/PHPMailerAutoload.php');
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username = 'xxx@xx.com';
$mail->Password = 'XXXXX';
$mail->SetFrom('XXX@XXX.com', 'FromEmail');
$mail->addAddress('XXX@XXX.com', 'ToEmail');
$mail->addAttachment("GeneratedPDFFiles/Invoices/Invoice $last_id.pdf");     
$mail->SMTPDebug  = 3;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; $mail->Debugoutput = 'echo';
$mail->IsHTML(true);

当我删除附件行时,电子邮件发送正常,但是在那里,没有发送电子邮件?

文件存在于目录中,所以这不是问题所在。

这里有几处错误。

首先我可以看到你使用的是旧版本的 PHPMailer,所以升级,最好使用 composer。

您正在创建这样的实例:

$mail = new PHPMailer(true);

true 意味着 PHPMailer 将抛出异常,但是您没有 try/catch 块包裹您的 PHPMailer 方法调用,因此当异常发生时,您的代码将死掉。在适当的地方添加 try/catch 块,或者删除 true 参数以通过 return 值来处理错误。

我预计它会死在这里:

$mail->addAttachment("GeneratedPDFFiles/Invoices/Invoice $last_id.pdf");     

当您说 "The file is present in the directory, so that's not the problem" 时,您是在假设这是真的 - 不要; 检查。如果文件不存在,或者脚本没有读取它的权限,此方法将抛出异常(除非您在构造函数中删除了 true 参数)。

您使用了相对路径,但您的工作目录可能与您想象的不一样。使用绝对路径更安全,例如在当前脚本的位置前添加(可能与 . 不同)。不管是什么原因,最好也检查 return 值:

$file = __DIR__ . "/GeneratedPDFFiles/Invoices/Invoice $last_id.pdf";
if (!$mail->addAttachment($file)) {
    die('Could not open file ' . $file);
}