使用PHP命令行发送邮件需编写脚本并运行,Linux下可借助mail()函数配合MTA如sendmail,Windows则推荐PHPMailer通过SMTP发送;示例包含mail()基础用法与PHPMailer配置步骤,并可通过crontab定时执行脚本实现自动化邮件发送。

在PHP中通过命令行发送邮件,通常不是直接使用“PHP命令”来完成,而是编写PHP脚本并结合命令行运行该脚本。重点在于使用PHP的邮件功能(如 mail() 函数或第三方库)配合SMTP配置来实现邮件发送。下面详细介绍如何在命令行环境下配置和发送邮件。
使用 mail() 函数发送邮件(适用于Linux环境)
PHP内置的 mail() 函数可以在命令行脚本中调用,但依赖系统已配置好邮件传输代理(MTA),如 sendmail 或 postfix。
- 确保服务器安装了 sendmail 或其他 MTA 软件
- 创建一个PHP脚本,例如 send_mail.php
示例代码:
<?php
$to = 'recipient@example.com';
$subject = '测试命令行邮件';
$message = '这是一封通过PHP命令行发送的邮件。';
$headers = 'From: sender@example.com' . "\r\n" .
'Reply-To: sender@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
<p>if (mail($to, $subject, $message, $headers)) {
echo "邮件发送成功\n";
} else {
echo "邮件发送失败\n";
}
?>
在终端执行:
立即学习“PHP免费学习笔记(深入)”;
php send_mail.php
注意:Windows系统默认不支持 mail(),需借助第三方库。
使用 PHPMailer 配置 SMTP 发送邮件
更可靠的方式是使用 PHPMailer,支持SMTP认证,跨平台兼容性好,适合命令行脚本。
- 通过 Composer 安装 PHPMailer:
composer require phpmailer/phpmailer
- 创建脚本 send_smtp.php
示例代码:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
<p>require 'vendor/autoload.php';</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1552" title="Programming Helper"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680263524608.jpg" alt="Programming Helper" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1552" title="Programming Helper">Programming Helper</a>
<p>AI代码自动生成器,在AI的帮助下更快地编程</p>
</div>
<a href="/ai/1552" title="Programming Helper" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p>$mail = new PHPMailer(true);</p><p>try {
// 使用SMTP
$mail->isSMTP();
$mail->Host = 'smtp.example.com'; // SMTP服务器
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com'; // 登录账号
$mail->Password = 'your_password'; // 授权码或密码
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;</p><pre class="brush:php;toolbar:false;">$mail->setFrom('from@example.com', '发件人');
$mail->addAddress('to@example.com', '收件人');
$mail->isHTML(false);
$mail->Subject = '命令行SMTP邮件';
$mail->Body = '这是一封通过PHP命令行发送的SMTP邮件。';
$mail->send();
echo "邮件已发送\n";} catch (Exception $e) { echo "邮件发送失败:{$mail->ErrorInfo}\n"; } ?>
在终端运行:
php send_smtp.php
配置 php.ini 中的 SMTP 参数(仅限Windows)
在Windows环境下,可修改 php.ini 直接设置默认SMTP参数,使 mail() 函数可用。
- 打开 php.ini 文件
- 修改以下配置:
SMTP = smtp.example.com smtp_port = 587 sendmail_from = sender@example.com
注意:这种方式限制较多,推荐使用 PHPMailer 等库替代。
定时任务中使用PHP命令发送邮件
结合 crontab(Linux)或计划任务(Windows),可定时执行PHP邮件脚本。
例如,在 Linux 的 crontab 中添加:
0 9 * * * /usr/bin/php /path/to/send_mail.php
每天上午9点自动发送邮件。
基本上就这些。核心是写好PHP脚本,选择合适方式(mail函数或PHPMailer),并在命令行正确执行。SMTP配置建议使用PHPMailer,灵活且稳定。










