php 发送SMTP邮件

PHP 发送smtp 邮件

*使用composer 引入 PHPMailer\PHPMailer *
端口号要改成 465 (默认25 端口被封)

public function sendEmail()
    {
        ### 邮箱的配置
        $config = require __DIR__ . '/../config/smtp.php';
       
        $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
        try {
            //Server settings
            $mail->SMTPDebug = 0;                                 // Enable verbose debug output
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = $config['host'];                        // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            //smtp登录的账号 
            $mail->Username = $config['username'];                // SMTP username
            //smtp登录的密码
            $mail->Password = $config['password'];                // SMTP password
            //设置使用ssl加密方式登录鉴权
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to
            $mail->CharSet='UTF-8';                          // 设置编码格式
            //Recipients
            $mail->setFrom($config['username'], $config['sign']);
            //设置收件人邮箱地址 该方法有两个参数 第一个参数为收件人邮箱地址
            // 第二参数为给该地址设置的昵称 不同的邮箱系统会自动进行处理变动 这里第二个参数的意义不大
            $mail->addAddress('[email protected]', '测试');         // Add a recipient
            //答复
            $mail->addReplyTo('[email protected]', '测试');
            // 抄送地址
            //$mail->addCC('[email protected]');
            //$mail->addBCC('[email protected]');

            //Attachments 附件(服务器上文件放置地址)
            $mail->addAttachment(WEBPATH.'public/uploadfile/'.get_attachment('608')['attachment'],'code.text');
            //Content
            $mail->isHTML(true);                                    // Set email format to HTML
            $mail->Subject = $config['subject'];
            $mail->Body = $config['body'].''.$config['sign'].'';
            $mail->AltBody = $config['altBody'];
            $mail->send();
            echo 'Message has been sent';
        } catch (Exception $e) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
    }

效果图

你可能感兴趣的:(邮件发送,php)