在ThinkPHP框架下进行邮件发送需要使用PHPMailer
库。首先,需要将PHPMailer
库添加到项目中,通常可以使用Composer进行安装。
安装完成后,可以在项目控制器中创建一个新的邮件对象,并设置SMTP服务器地址、端口号、发送方邮箱和SMTP邮箱密码等参数。例如:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
$mail->isSMTP(); // 使用 SMTP
$mail->Host = 'smtp.example.com'; // SMTP服务器地址
$mail->SMTPAuth = true; // 启用 SMTP 验证
$mail->Port = 465; // SMTP 端口号
$mail->CharSet = 'UTF-8'; // 设置字符集
$mail->SMTPSecure = 'ssl'; // 启用 SSL 加密
$mail->Username = 'sender@example.com'; // 发送方邮箱地址
$mail->Password = 'password'; // SMTP 邮箱密码
$mail->setFrom('sender@example.com', 'Sender Name'); // 设置发送方信息
$mail->addAddress('recipient@example.com', 'Recipient Name'); // 添加收件人信息
$mail->Subject = 'Subject'; // 邮件主题
$mail->Body = 'Email body'; // 邮件内容
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
以上代码示例使用了SSL加密方式,如果使用TLS加密方式则需要修改$mail->SMTPSecure
的值为‘tls’。
最后,通过调用send()
方法即可发送邮件。如有发送失败则可以通过访问$mail->ErrorInfo
获取错误信息。