1、下载thinkPHP
地址:http://www.thinkphp.cn/down/1278.html,本文所用的tp5版本号为5.0.24
2、phpmailer的下载
从 github 上下载: https://github.com/PHPMailer/PHPMailer/,使用git克隆下来,然后在tp5项目目录下的vendor新建一个phpmailer文件夹,将下载的phpmailer文件放到该目录下
3、编写发送邮件的脚本文件
在tp5项目的application目录下的公共文件common.php添加代码,发送之前需要拥有自己的邮件服务器,测试的时候其实用自己申请的免费邮箱最方便了,不需要自己再搭建服务器了
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//加载类
require __DIR__.'/../vendor/PHPMailer/PHPMailer/src/Exception.php';
require __DIR__.'/../vendor/PHPMailer/PHPMailer/src/PHPMailer.php';
require __DIR__.'/../vendor/PHPMailer/PHPMailer/src/SMTP.php';
function mailTo($toUser,$title,$content){
//toUser:发送给谁,$title:标题,content:内容
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//服务器配置
$mail->CharSet ="UTF-8"; //设定邮件编码
$mail->SMTPDebug = 0; // 调试模式输出
$mail->isSMTP(); // 使用SMTP
$mail->Host = 'smtp.163.com'; // SMTP服务器
$mail->SMTPAuth = true; // 允许 SMTP 认证
$mail->Username = '邮箱用户名'; // SMTP 用户名 即邮箱的用户名
$mail->Password = '密码或者授权码'; // SMTP 密码 部分邮箱是授权码(例如163邮箱)
$mail->SMTPSecure = 'ssl'; // 允许 TLS 或者ssl协议
$mail->Port = 465; // 服务器端口 25 或者465 具体要看邮箱服务器支持
$mail->setFrom('xxxx@163.com', 'Mailer'); //发件人
$mail->addAddress($toUser); // 收件人
//$mail->addAddress('ellen@example.com'); // 可添加多个收件人
$mail->addReplyTo('xxxx@163.com', 'info'); //回复的时候回复给哪个邮箱 建议和发件人一致
//$mail->addCC('cc@example.com'); //抄送
//$mail->addBCC('bcc@example.com'); //密送
//发送附件
// $mail->addAttachment('../xy.zip'); // 添加附件
// $mail->addAttachment('../thumb-1.jpg', 'new.jpg'); // 发送附件并且重命名
//Content
$mail->isHTML(true); // 是否以HTML文档格式发送 发送后客户端可直接显示对应HTML内容
$mail->Subject =$title; //发送标题
$mail->Body = $content; //发送的内容
// $mail->AltBody = '如果邮件客户端不支持HTML则显示此内容';
$mail->send();
echo '邮件发送成功';
} catch (Exception $e) {
echo '邮件发送失败: ', $mail->ErrorInfo;
}
}
4、邮箱开启POP3/SMTP/IMAP服务
本文以163邮箱为例,登录网页版163邮箱,勾选开启POP3/SMTP/IMAP服务,如果之前没有设置过客户端授权码,会弹出设置客户端授权码进行设置,该授权码将代替步骤3中common.php文件中的password。
5、phpmailer的使用
将以上步骤做完后,就可以在tp5项目中使用了,比如在index模块的index控制器下的index方法中使用