邮件发送
1.安装PHPMailer扩展。
composer require phpmailer/phpmailer
2.配置文件设置邮件信息
'email_config'=>[
'mail_host' => 'smtp.163.com',//邮件发送域名
'mail_port' => '994',//邮件发送端口,994/465
'mail_user' => 'test@163.com',//邮箱账号
'mail_password' => 'XXXXXXXXX',//邮件发送授权码
'mail_form' => 'test@163.com',//显示的发件人邮箱(邮箱账号)
'mail_secure' => 'ssl'//ssl网络模式
],
3.封装邮件发送类
<?php
/**
* 邮件助手类
*/
namespace app\service;
use PHPMailer\PHPMailer\PHPMailer;
use think\Config;
use think\Exception;
use think\Url;
// https://packagist.org/packages/phpmailer/phpmailer
class Mail
{
private $Form = '';
private $Host='';
private $Username='';
private $Password = '';
private $Secure = '';
private $Port = '';
public function __construct()
{
$config = Config::get('email_config');
$this->Form = $config['mail_form'];
$this->Host = $config['mail_host'];
$this->Username = $config['mail_user'];
$this->Password = $config['mail_password'];
$this->Secure = $config['mail_secure'];
$this->Port = $config['mail_port'];
}
/**
* @param $toEmail 接受邮件用户
* @param $Subject 邮件标题
* @param null $content 邮件内容
* @param null $html 邮件模板
* @param null $attachment 邮件附件
* @throws \PHPMailer\PHPMailer\Exception
*
*/
public function sendEmail($toEmail,$Subject,$content=null,$html=null,$attachment=null){
$email = new PHPMailer();
try {
// 设置邮件格式
$email->isSMTP();
// 设置有见程序使用SMTP 格式
$email->Host = $this->Host;
// 设置有见内容的编码
$email->CharSet = 'UTF-8';
// 启用SMTP验证
$email->SMTPAuth = true;
// SMTP username
$email->Username = $this->Username;
// SMTP password
$email->Password = $this->Password;
// 启用TLS加密,`ssl`也被接受
$email->SMTPSecure = $this->Secure;
// 连接的TCP端口
$email->Port = $this->Port;
//设置发件人
$email->setFrom($this->Form, '讯飞产业加速中心');
// 设置收件人
$email->addAddress($toEmail);
// 设置如果收件人回复邮件 直接显示我的邮件
$email->addReplyTo($this->Form);
if ($attachment){
$email->AddAttachment('./PDF/'.basename($attachment),basename($attachment));
}
$email->isHTML();
$email->Subject = $Subject;
if ($html){
$content = file_get_contents($html);
}
$email->Body = $content;
if ($email->send()){
return 'success';
}else{
echo "Mailer Error: ".$email->ErrorInfo;// 输出错误信息
}
}catch (Exception $e){
echo "Mail Error:" . $e->ErrorInfo;
}
}
}
4.控制器调用
$sendEmail = new Mail();
$sendEmail->sendEmail($admin_id['email'],'邮件标题','邮件内容');

浙公网安备 33010602011771号