在 Ubuntu 上让 PhpStorm 项目通过 SMTP 发信的正确做法
PhpStorm 不提供内置的 SMTP 账号配置,邮件由项目代码或运行环境发出。推荐在 Ubuntu 项目中使用 PHPMailer 直连邮件服务商的 SMTP,或在系统侧配置 Postfix 仅发送 作为本地 SMTP 中继。下面给出两种方式的实操步骤与排错要点。
方式一 使用 PHPMailer 直连 SMTP(推荐)
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// 服务器设置
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // 调试时可开启
$mail->isSMTP();
$mail->Host = 'smtp.example.com'; // 例如:smtp.qq.com
$mail->SMTPAuth = true;
$mail->AuthType = SMTP::AUTH_LOGIN; // 多数服务商使用 LOGIN
$mail->Port = 587; // 或 465
$mail->SMTPSecure = SMTP::ENCRYPTION_STARTTLS; // 587 用 STARTTLS;465 用 ENCRYPTION_SMTPS
// 凭据
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password_or_app_password';
// 发件人与收件人
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Recipient');
// 内容
$mail->isHTML(true);
$mail->Subject = '测试邮件';
$mail->Body = '这是一封来自 <b>PHPMailer</b> 的测试邮件。';
$mail->AltBody = '这是一封纯文本备用内容。';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
方式二 配置 Postfix 仅发送 SMTP 中继(系统级方案)
常见服务商 SMTP 参数示例
在 PhpStorm 中的运行与调试建议