PHP发送邮件[Thinkphp直接使用,其他框架修改使用] 1.安装 composer require phpmailer/phpmailer 2.填写配置表
配置文件mail.php <?php return [ 'driver' => 'smtp', // 邮件驱动, 支持 smtp|sendmail|mail 三种驱动 'host' => '', // SMTP服务器地址 'port' => '', // SMTP服务器端口号,一般为25 'username' => '', // 发件邮箱地址 'password' => '', // 发件邮箱密码 'name' => '', // 发件邮箱名称 'content_type' => 'text/html', // 默认文本内容 text/html|text/plain 'charset' => 'utf-8', // 默认字符集 'security' => 'ssl', // 加密方式 null|ssl|tls, QQ邮箱必须使用ssl 'sendmail' => '/usr/sbin/sendmail -bs', // 不适用 sendmail 驱动不需要配置 'debug' => true, // 开启debug模式会直接抛出异常, 记录邮件发送日志 'left_delimiter' => '{', // 模板变量替换左定界符, 可选, 默认为 { 'right_delimiter' => '}', // 模板变量替换右定界符, 可选, 默认为 } 'log_driver' => '', // 日志驱动类, 可选, 如果启用必须实现静态 public static function write($content, $level = 'debug') 方法 'log_path' => '', // 日志路径, 可选, 不配置日志驱动时启用默认日志驱动, 默认路径是 /path/to/tp-mailer/log, 要保证该目录有可写权限, 最好配置自己的日志路径 'embed' => 'embed:', // 邮件中嵌入图片元数据标记 ];3.发送邮件代码
<?php namespace app\api\controller; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; use think\facade\Request; class Mail extends Common { /** * 发送邮件 * @return void */ public function sendMail() { $to = Request::post('to');//接收人,多人传数组 $subject = Request::post('subject');//标题 $contents = Request::post('contents');//内容 $mail = new PHPMailer(true); try{ //服务器配置 $mail->CharSet ="UTF-8"; //设定邮件编码 $mail->SMTPDebug = 0; // 调试模式输出 $mail->isSMTP(); // 使用SMTP $mail->Host = config('mail.host'); // SMTP服务器 $mail->SMTPAuth = true; // 允许 SMTP 认证 $mail->Username = config('mail.username'); // SMTP 用户名 即邮箱的用户名 $mail->Password = config('mail.password'); // SMTP 密码 部分邮箱是授权码(例如163邮箱) $mail->SMTPSecure = config('mail.security'); // 允许 TLS 或者ssl协议 $mail->Port = config('mail.port'); // 服务器端口 25 或者465 具体要看邮箱服务器支持 $mail->setFrom(config('mail.username')); //发件人 if(!is_array($to)){ $mail->addAddress($to); }else{ foreach($to as $v){ $mail->addAddress($v); } } //Content $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $contents; $mail->AltBody = '客户端不支持查看,请转到PC端查看'; $mail->send(); echo '短信发送成功'; } catch (Exception $e) { echo '发送失败'; } } }