PHPMailer
1/下载工具:https://github.com/PHPMailer/PHPMailer
2/放入项目内
3/上地址,往下看有demo示例代码,复制粘贴到php文件中
实例代码:
<?php
namespace App\Service;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class MailSms
{
//发送商
const HOST='smtp.qq.com';
//发件人邮箱
const USERNAME='1111111@qq.com';
//发件箱授权码
const PASSWORD='jjtvrqkawaddwfe';
//发送模板
const TEMPLATE='您的验证码是{code},请在10分钟内填写。';
//是否debug 测试环境使用
const DEBUG=true;
//实例
protected $mail;
public function __construct(){
$this->mail=new PHPMailer;
}
/**
* target 发送给谁 收件人的邮箱
* subject 主题
* code 验证码
*/
public function sendMail($target,$subject,$code)
{
$content = str_replace('{code}',$code,self::TEMPLATE);
try{
$this->mail->SMTPDebug=self::DEBUG;
$this->mail->isSMTP();
$this->mail->Host=self::HOST;//服务器
$this->mail->SMTPAuth=true;//是否开启SMTP认证
$this->mail->Username=self::USERNAME;//发件人邮箱
$this->mail->Password=self::PASSWORD;//发件箱授权码
$this->mail->SMTPSecure='tls';//启用TLS加密,' ssl '也接受
$this->mail->Port='25';//端口
$this->mail->CharSet='UTF-8';//设置邮件内容编码
$this->mail->setFrom(self::USERNAME); //发件人
//$this->mail->addAttachment('/var/tmp/file.tar.gz');//附件
//$this->mail->addAttachment('/tmp/image.jpg', 'new.jpg');//附件重命名
$this->mail->addAddress($target);//发送给谁
$this->mail->isHTML(true);
$this->mail->Subject=$subject;
$this->mail->Body=$content;
//$this->mail->AltBody ='This is the body in plain text for non-HTML mail clients';
if($this->mail->send()){
...
}else{
...
}
}catch(Exception $e){
...
}
}
}
说明:邮件授权码,我使用的是qq邮箱,打开QQ邮箱
laravel自带的Mail组件
.env配置
MAIL_HOST=smtp.qq.com //邮件服务器 这是qq的
MAIL_PORT=25
MAIL_USERNAME=1111111@qq.com //发送人邮箱
MAIL_PASSWORD=jjtvrqkxiumtjebc //发送的授权码 同上
php文件
use Mail;
$flag = Mail::send('emails.welcome',['code'=>$code],function($message)use($email){
$message ->to($email)->subject('测试数据');
});
if($flag){....
//emails.welcome是模板文件,['code'=>$code]是传递的变量
在resource/下新建emails文件夹,建立邮件模板welcome.blade.php,内容如您的验证码是 {{$code}},10分钟内有效。
end;