1.下载PHPMailer
composer require phpmailer/phpmailer
2.开启邮箱的IMAP/SMTP服务
3.前端代码
忽略…
4.后端代码
public function sendMail($receiver,$theme,$content)
{
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; // 是否开启smtp的debug进行调试 ,0关闭,1开启
$mail->isSMTP(); // 启用SMTP
$mail->CharSet='utf-8'; //设置字符编码
$mail->Host = 'smtp.qq.com';// SMTP服务器,这里是qq邮箱
$mail->SMTPAuth = true;// 启用SMTP认证
$mail->Username = 'xxxxxxxxxx@qq.com';// 发送邮件的邮箱,即自己的邮箱
$mail->Password = 'qqdlvigkisnqebdd';// 授权码 步骤2中获取到的
$mail->SMTPSecure = 'ssl';// 加密方式为tls或者ssl,根据需求自己改
$mail->Port = 465;// 端口号
//Recipients
$mail->setFrom('xxxxxxxxxx@qq.com', '微风细雨'); //从哪发送的邮件,和上面的$mail->Username一样,后面是发送者的昵称,可以改
$mail->addAddress($receiver);// 增加一个接受者的邮箱,这里用变量
//$mail->addAddress('ellen@example.com');// 可以增加多个
// $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
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $theme;//标题 主题
$mail->Body = $content;//正文
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';////当邮件不支持html时备用显示,可省略
$mail->send();//发送邮件
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}