当前位置: 首页> 最新文章列表> PHP使用PHPMailer通过SMTP发送邮件的详细教程

PHP使用PHPMailer通过SMTP发送邮件的详细教程

gitbox 2025-08-08

什么是SMTP邮件发送

SMTP(简单邮件传输协议)是互联网中负责邮件传递的标准协议。通过SMTP协议,PHP开发者可以实现邮件的发送,支持文本、附件甚至图片等内容的发送功能。

安装PHPMailer库

PHPMailer是PHP中广泛使用的邮件发送类库,支持SMTP协议及多种邮件格式。安装PHPMailer可以通过Composer,命令如下:

<span class="fun">composer require phpmailer/phpmailer</span>

引入PHPMailer类

安装完成后,在PHP脚本中引入自动加载文件,以便使用PHPMailer类:

<span class="fun">require 'vendor/autoload.php';</span>

配置SMTP参数

创建PHPMailer对象并设置SMTP服务器相关信息,包括服务器地址、认证信息和加密方式:

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

请根据实际情况替换以上参数中的SMTP服务器地址、用户名和密码。

设置邮件内容

指定发件人、收件人、邮件主题和正文内容:

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';

发送邮件

调用PHPMailer的send()方法执行邮件发送操作,并根据结果进行提示:

if ($mail->send()) {
    echo 'Email sent successfully.';
} else {
    echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}

完整示例代码

require 'vendor/autoload.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
if ($mail->send()) {
    echo 'Email sent successfully.';
} else {
    echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}

总结

本文介绍了如何使用PHPMailer库在PHP中通过SMTP协议发送邮件,包含从安装库、引入类、配置SMTP参数到设置邮件内容及发送的完整步骤。掌握这些内容后,您可以灵活地将邮件功能集成到自己的PHP项目中。