所需要的扩展类库:https://github.com/timeblog/thinphp5-case/tree/master/mailer
<?php
namespace app\demo\controller;
use think\Loader;
class Mail
{
public function index(){
$emails=['920668625@qq.com','xxxxxxxx@qq.com','xxxxxxxxx@qq.com'];
if(is_array($emails)){
foreach($emails as $emails){
$result=self::send_email($emails,'测试邮件','内容<br>...');
}
}else{
$result=self::send_email($emails,'测试邮件','内容<br>...');
}
if($result['error']!==0){
return '发送邮件失败<br>'.$result['message'];
}
}
/**
* 发送邮件
* @param string $address 需要发送的邮箱地址 发送给多个地址需要写成数组形式
* @param string $subject 标题
* @param string $content 内容
* @return boolean 是否成功
*/
private function send_email($address,$subject,$content){
$email_smtp=config('MAIL_CONFIG.EMAIL_SMTP');//smtp
$email_username=config('MAIL_CONFIG.EMAIL_USERNAME');// 账号
$email_password=config('MAIL_CONFIG.EMAIL_PASSWORD');//是授权码;不是登录的密码,否则SMTP connect() failed;
$email_from_name=config('MAIL_CONFIG.EMAIL_FROM_NAME');// 发件人昵称
$email_smtp_secure='';// 如果使用QQ邮箱;需要把此项改为 ssl
$email_port='25';// 如果使用QQ邮箱;需要把此项改为 465
if(empty($email_smtp) || empty($email_username) || empty($email_password) || empty($email_from_name)){
return ["error"=>1,"message"=>'邮箱配置不完整'];
}
Loader::import('mailer.Phpmailer');
Loader::import('mailer.Smtp');
$phpmailer=new \Phpmailer();
// 设置PHPMailer使用SMTP服务器发送Email
$phpmailer->IsSMTP();
// 设置设置smtp_secure
$phpmailer->SMTPSecure=$email_smtp_secure;
// 设置port
$phpmailer->Port=$email_port;
// 设置为html格式
$phpmailer->IsHTML(true);
// 设置邮件的字符编码'
$phpmailer->CharSet='UTF-8';
// 设置SMTP服务器。
$phpmailer->Host=$email_smtp;
// 设置为"需要验证"
$phpmailer->SMTPAuth=true;
// 设置用户名
$phpmailer->Username=$email_username;
// 设置密码
$phpmailer->Password=$email_password;
// 设置邮件头的From字段。
$phpmailer->From=$email_username;
// 设置发件人名字
$phpmailer->FromName=$email_from_name;
// 添加收件人地址,可以多次使用来添加多个收件人
$phpmailer->AddAddress($address);
// 设置邮件标题
$phpmailer->Subject=$subject;
// 设置邮件正文
$phpmailer->Body=$content;
// 发送邮件。
if(!$phpmailer->Send()) {
$phpmailererror=$phpmailer->ErrorInfo;
return array("error"=>1,"message"=>$phpmailererror);
}else{
return array("error"=>0);
}
}
}