PHPMailer 5.2在旧版PHP环境中的应用
前言
近期在实现邮件发送功能时遇到不少挑战,作为初学者难免踩坑。经过反复调试,终于成功解决了PHPMailer的使用问题,现将具体过程整理如下供参考。
PHPMailer是一个功能齐全的PHP邮件创建与传输类库。
在PHP开发环境中,开发者可以利用该工具轻松构建并发送电子邮件。
最新版本(20261012)是PHPMailer 6.0.5,这个无法兼容php5.5以下的环境。由于我需要维护php5.3的项目,需要切换到PHPMailer5.2来发送邮件。
可通过以下链接获取历史版本资源:https://github.com/PHPMailer/PHPMailer/releases/tag/v5.2.24
接下来将直接进入具体的操作环节,省略冗余介绍。
基本使用方法
完成下载与解压后,新建一个用于测试的Demo文件。
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.exmail.qq.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxx@qq.com'; // SMTP username
$mail->Password = 'yourpassword'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->setFrom('fromWho@qq.com', 'Mailer');
$mail->addAddress('toWhom@qq.com', 'Ryan Miao'); // Add a recipient
$mail->addAddress('ellen@example.com'); // Name is optional
// $mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body in bold!';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
启用SMTPDebug参数有助于实时查看通信日志,便于排查问题。
`0` 无输出 `1` 仅显示命令 `2` 显示数据与命令 `3` 同2,额外包含连接状态信息 `4` 低级别数据输出
若发生错误,相关信息将记录在 $mail->ErrorInfo对象中。
将代码保存为mail.php文件,随后在命令行中运行该脚本。
php mail.php
执行后即可在终端看到详细的通信日志,并确认邮件已成功发出。
总结
以上内容涵盖了本文的核心知识点,希望对各位的学习或工作有所助益。如有任何疑问,欢迎留言交流,感谢大家的支持。