第一种方式
第一步、(方式有很多我只是用了其中一个案例)
composer require phpmailer/phpmailer
第二步、在自定义控制器引入
use PHPMailer\PHPMailer\PHPMailer;
第三步、发送邮箱
$toemail = '***@qq.com/***@sina.cn';//发送给谁 $mail = new PHPMailer(); $mail->isSMTP(); //使用smtp鉴权方式发送邮件 $mail->CharSet = 'utf8'; //设置编码 $mail->Host = 'smtp.sina.cn'; //qq邮箱smtp邮箱 $mail->SMTPAuth = true; //是否需要认证身份 $mail->Username = "***@qq.com/***@sina.cn"; //发送方邮箱 $mail->Password = "*****"; //发送方smtp密码,去qq或者新浪等其他邮箱平台获取授权码密码 $mail->SMTPSecure = 'ssl'; //使用的协议 $mail->Port = 465; //qq邮箱接收的端口号//新浪端口无需填写 $mail->setFrom('***@qq.com/***@sina.cn', '测试'); //定义邮件及标题 $mail->addAddress($toemail, '成功了!'); //要发送的地址和设置地址的昵称 $mail->addReplyTo('***@qq.com/***@sina.cn'); //回复地址 $mail->Subject = "测试"; //添加该邮件的主题 $mail->Body = '发送成功了'; //该邮件内容 //如果发送失败 if (!$mail->send()) { return json(['code' => 400 , 'msg'=>'邮件发送失败']); } else { return json(['code' => 200 , 'msg'=>'邮件发送成功']); }
QQ邮箱的授权码,(密码)
新浪邮箱的授权码(密码)
其他邮箱自己可以去试试
第二种方式
第一步、在config/app内配置邮箱参数
第二步、安装扩展
composer require swiftmailer/swiftmailer
第三步、在自定义控制器引入
use Swift_Mailer; use Swift_SmtpTransport; use Swift_Message;
第四步、发送邮箱
public function sendMail() { $to="******@qq.com";//发送方邮箱地址 $subject="发送";//发送邮箱标题 $body="邮箱发送成功了";//发送邮箱内容 $transport = (new Swift_SmtpTransport(config('app.mail.host'), config('app.mail.port'), config('app.mail.encryption'))) ->setUsername(config('app.mail.username')) ->setPassword(config('app.mail.password')); $mailer = new Swift_Mailer($transport); $message = (new Swift_Message($subject)) ->setFrom([config('app.mail.username') => '测试'])->setTo([$to])->setBody($body, 'text/html'); $result = $mailer->send($message); if($result&&$result=='1'){ return json(['code' => 200 , 'msg'=>'邮件发送成功']); }else { return json(['code' => 400 , 'msg'=>'邮件发送失败']); } }