PHPMailer发送邮件

1. 下载 PHPMailer#

composer require phpmailer/phpmailer

2. 开启邮箱的 IMAP/SMTP 服务#

PHPMailer使用

PHPMailer使用

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}";
        }
    }
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。