2022-07-07 10:01 ThinkPHP 88 梁俊威
国内网站、软件大多数已经淘汰使用邮箱进行沟通,但是相对海外而言,大多数老外使用的主要还是邮箱,所以我们需要开发发送邮件功能,这个功能已经很成熟了,所以简单上个码。
安装phpmailer扩展包
composer require phpmailer/phpmailer
在根目录下运行Composer进行安装。
封装Email类
<?php namespace app\common\controller; use think\App; use think\facade\Config; use think\Request; use think\View; use think\Db; use app\BaseController; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; use app\common\model\EmailConfig; class Email { /* * 发送邮件 * @param $toEmail String 收件人邮箱 * @param $toName String 收件人昵称 * @param $title String 邮件标题 * @param $content String 邮件内容,支持HTML格式 * @return bool **/ public function send($toEmail, $toName, $title, $content){ $config = (new EmailConfig())->getConfig();// 注意这里要调整成你获取邮箱配置的调用方式 $mail = new PHPMailer(); $mail->isSMTP(); //使用smtp鉴权方式发送邮件 $mail->CharSet = 'utf8'; //设置编码 $mail->SMTPAuth = true; //是否需要认证身份 $mail->Host = $config['host']; //qq邮箱smtp邮箱 $mail->Username = $config['username']; //发送方邮箱 $mail->Password = $config['password']; //发送方smtp密码 $mail->Port = $config['port']; //qq邮箱接收的端口号 $mail->SMTPSecure = $config['secure']; //使用的协议 // $mail->SMTPDebug = 1; // 开启调试 $mail->isHTML(true); // 是否以HTML格式发送 $mail->setFrom($config['send_email'], $config['send_name']); //发件邮箱,发件人 $mail->addAddress($toEmail, $toName); //收件人邮箱,收件昵称 $mail->addReplyTo($config['send_email'], $config['send_name']); //回复邮箱,回复人 $mail->Subject = $title; //添加该邮件的主题 $mail->Body = $content; //该邮件内容 $result = $mail->send(); if(!$result){ // $mail->ErrorInfo 发送错误信息 throw_exception("2001", $mail->ErrorInfo); } return true; } }
需要使用的时候直接初始化类调用即可。
若无特殊说明,本站点所有内容均为原创,转载请说明出处!