thinkphp5.1使用PHPMailer
程序员文章站
2022-04-26 14:07:02
...
- composer下载PHPMailer
composer require phpmailer/phpmailer
- 新建文件Mail.php,如下图
- Mail.php代码如下
/**
* Created by PhpStorm.
* User: 17839
* Date: 2020/3/22
* Time: 16:04
*/
namespace app\common\lib\Mail;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
class Mail
{
public function sendMail($email, $username, $subject = '', $body = '')
{
$mail = new PHPMailer(true);
// try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF; // 是否开启发送调式
$mail->isSMTP(); // 设置发送协议是smtp
$mail->Host = 'smtp.qq.com'; // qq邮箱会好用一些
// 设置邮件内容的编码
$mail->CharSet='UTF-8';// SMTP服务地址
$mail->SMTPAuth = true; // 是否开启MSTP验证
$mail->Username = config('mail.email'); // 发件人的邮箱地址
$mail->Password = config('mail.password'); // 发件人邮箱授权码
//$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
//$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom(config('mail.email'), '欢迎欢迎'); // 发送邮件的名称
$mail->addAddress($email, $username); // 添加收件人的邮箱地址
//$mail->addAddress('aaa@qq.com'); // 第二个参数可选
//$mail->addReplyTo('aaa@qq.com', 'Information'); // 添加恢复地址
//$mail->addCC('aaa@qq.com'); // 抄送地址
//$mail->addBCC('aaa@qq.com');
// Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // 添加附件
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // 设置邮件的内容格式
$mail->Subject = $subject; // 邮件的主题
$mail->Body = $body; // 邮件的正文
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
// 当内容不能正常现实的时候显示的内容
$res = $mail->send();
if (!$res) {
return $mail->ErrorInfo;
}
return true;
// } catch (Exception $e) {
// echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
// }
}
}
- 在app/index/controller/index.php试用自己封装的类库
namespace app\index\controller;
use app\common\lib\alidayu\AliSms;
use app\common\lib\express100\Express;
use app\common\lib\Mail\Mail;
use app\common\lib\sms\Sms;
use think\Controller;
class Index extends Controller
{
public function index()
{
// // 云之讯
//// $sms = new Sms();
// // 阿里大鱼
// $sms = new AliSms();
//
// // 用自己的手机号实验
// $phone = '17515401314';
// $code = self::getCode();
// $data = $sms->smsSend($phone, $code);
// halt($data);
$email = 'aaa@qq.com';
$username = 'Tom';
$subject = '欢迎**';
$body = '您的***:' . $this->getCode();
$mail = new Mail();
$res = $mail->sendMail($email, $username, $subject, $body);
if ($res == true) {
echo '发送成功';
}
}
/**
* 随机产生验证码 4位或6位
* @param int $num [几位数验证码]
* @return int
*/
public static function getCode($num = 4)
{
if ($num == 4) {
return rand(1000, 9999);
} else {
return rand(100000, 999999);
}
}
}
- 访问 http://<自己的域名>,得到如下结果
ok