安装phpmailer
composer require phpmailer/phpmailer
封装一个 phpMail 服务在 services中
<?php
namespace App\Services;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
class PhpMail
{
//两个参数,一个收件人,一个邮件内容
public function send($recipient,$contentString)
{
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0; // 调试模式输出
$mail->CharSet ="UTF-8"; //设定邮件编码 可以不写,默认就是UTF-8
$mail->isSMTP(); // 使用SMTP
$mail->Host = 'smtp.qq.com'; // SMTP服务器
$mail->SMTPAuth = true; // 允许 SMTP 认证
$mail->Username = 'xxxxx@qq.com'; // SMTP 用户名 即邮箱的用户名
$mail->Password = 'xxxxxxxxxxxx'; // SMTP 密码 部分邮箱是授权码(例如163邮箱)
$mail->SMTPSecure = 'ssl'; // 允许 TLS 或者ssl协议
$mail->Port = 465; // 服务器端口 25 或者465 具体要看邮箱服务器支持
// 发送人是谁,怎么称呼?
$mail->setFrom('xxxxx@qq.com', '守明大大');
// 要发给谁?用什么来称呼
$mail->addAddress("$recipient", '尊敬的用户');
// 收件人可以多写几个,可以一并发送
// $mail->addAddress('ellen@example.com');
$mail->addReplyTo('1843395688@qq.com', 'reply');
//内容设置
// 是否以html格式发送
$mail->isHTML(true);
//Set email format to HTML
// 这是邮件标题
$mail->Subject = '这是给您的一封邮件';
$mail->Body = " <b>$contentString</b>";
$mail->AltBody = "$contentString";
// 发送
$mail->send();
return '邮件发送成功';
} catch (Exception $e) {
return "邮件发送失败: {$mail->ErrorInfo}";
}
}
}
收件人可以多写几个 ,将 $mail->addAddress("$recipient", '尊敬的用户'); 写在循环中即可
使用
public function test()
{
$mail=new PhpMail();
$error= $mail->send('xxxxxxx@139.com','123456');
dump($error);
}