1.composer 下载 PHPMailer 类
composer require phpmailer/phpmailer
下完后在 vendor 文件夹下会有 phpmailer 文件夹,如果不使用命名空间,就自行找到所需依赖并 require 吧
2. 编码:
最近有什么开心的事情吗?有在努力向上生活吗
AOF;
try {
$this->setSmtp($mail);
$this->setTitleAndContent($mail, $title, $content);
$mail->send();
return json([
'code' => 200,
'msg' => '邮件发送成功'
]);
} catch (Exception $e) {
return json([
'code' => 405,
'msg' => '发送失败',
'reason' => $mail->ErrorInfo
]);
}
}
public function setSmtp($mail)
{
$mail->CharSet = "UTF-8"; // 设定邮件编码
$mail->SMTPDebug = 0; // 调试模式输出
$mail->isSMTP(); // 使用SMTP
$mail->Host = $this->host; // SMTP服务器(这里用的qq邮箱,倘若是网易邮箱则设置smtp.163.com,其余邮箱请自行查找并设置)
$mail->SMTPAuth = true; // 允许 SMTP 认证
$mail->Username = $this->userName; // SMTP 用户名(即邮箱的用户名)
$mail->Password = $this->password; // SMTP 密码(邮箱授权码,非邮箱密码,怎么获取授权码请查看底部参考资料)
$mail->SMTPSecure = 'ssl'; // 允许 TLS 或者ssl协议
$mail->Port = 465; // 服务器端口 25 或者465(具体要看邮箱服务器支持,这里qq邮箱设置465端口)
$mail->setFrom($this->userName, $this->userName); // 发件人
$this->setPeople($mail, '165xxxx743@qq.com'); // 收件人
$this->setPeople($mail, '271xxxxx41@qq.com'); // 收件人
$mail->addReplyTo($this->userName, 'info'); // 回复的时候回复给哪个邮箱 建议和发件人一致
// $this->setAttachments($mail);
// $mail->addCC('cc@example.com'); // 抄送
// $mail->addBCC('bcc@example.com'); // 密送
}
public function setPeople($mail, $mailbox)
{
$mail->addAddress($mailbox); // 收件人
}
public function setAttachments($mail, $filePath = '', $type = '0', $newName = '新文件名称')
{
if (empty($type)) {
$mail->addAttachment($filePath); // 添加附件
} else {
$mail->addAttachment($filePath, $newName); // 添加附件并且重命名
}
}
public function setTitleAndContent($mail, $title, $content)
{
$mail->Subject = $title;
$mail->Body = $content;
$mail->isHTML(true); // 是否以HTML文档格式发送 发送后客户端可直接显示对应HTML内容
$mail->AltBody = '好像您的邮箱不支持html展示呢~'; // 如果邮件客户端不支持HTML则显示此内容
}
3. 效果展示:
补充:
因为这些大厂的邮箱服务器会对 IP 进行检测,如果在某个时间发送特别频繁的话,会出现发送失败的情况;所以不要在像我一样在 for 循环里测试... 不然就会出现:SMTP Error: Could not authenticate 搞得怀疑人生...
如果等待半小时后这个错误还出现,那就参考下面资料重新配置一下 smtp 设置,生成授权码并替换吧。
PHP 使用 phpmailer 发送电子邮件 | 菜鸟教程
使用 QQ 邮箱发送邮件,QQ 邮箱的 smtp 设置



