php 结合 PHPMailer 批量发送邮件。

(141) 2024-04-25 19:01:01

1、下载 PHPMailer: https://sourceforge.net/projects/phpmailer/

2、文件放到项目中,加载引入到文件中。

3、php代码。

<?php
/**
 * Created by PhpStorm.
 * User: jackhhy
 * Date: 2019/2/14-10:44
 * FileName: MaileController.php
 */

class MaileController extends Common
{

    public function __construct()
    {
        parent::__construct();
    }


    /**
     * @throws Exception
     * 发送邮件
     */
    public function indexAction(){
        if ($_POST){
            //邮箱验证表达式
            $regex="/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
            $data=$_POST;
            $adre=@explode(",",$data['maile']);
            //去除空值
            $cont=$this->array_remove_empty($adre);
            //
            if (count($cont) >1){
                $arr=[];
                foreach ($cont as $v){
                    //验证邮箱
                    $result = preg_match($regex,$v);
                    if (!$result){
                        unset($v);
                    }else{
                        $arr[]=$v;
                    }
                }
               $address=$arr;
            }else{
                $result = preg_match($regex,$cont[0]);
                if (!$result){
                    exit(error("接收人邮箱有误"));
                }
                $address=$cont[0];
            }
            //发送邮件
           $res=$this->Send_maile($address,$data['content'],$data['subject'],$data['nickname'],$data['username'],$data['password']);
            if ($res['error']==0){
                exit(success("发送成功"));
            }else{
                exit(error("发送失败-".$res['message']));
            }
        }

        $this->view->display('dan/maile');
    }


    /**
     * @param $address
     * @param $content
     * @param $nick
     * @param $user
     * @param $pass
     * @throws Exception
     */
    private function Send_maile($address,$content,$sub,$nick,$user,$pass){
        require_once APP_ROOT."/extensions/mailer/PHPMailer.php";
        require_once APP_ROOT."/extensions/mailer/SMTP.php";
        // 实例化PHPMailer核心类
        $mail = new PHPMailer();
       // 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
        $mail->SMTPDebug = 0;
        $mail->CharSet = "UTF-8";//设置信息的编码类型
// 使用smtp鉴权方式发送邮件
        $mail->isSMTP();
// smtp需要鉴权 这个必须是true
        $mail->SMTPAuth = true;
// 链接qq域名邮箱的服务器地址
        $mail->Host = 'smtp.qq.com';
// 设置使用ssl加密方式登录鉴权
        $mail->SMTPSecure = 'ssl';
// 设置ssl连接smtp服务器的远程服务器端口号
        $mail->Port = 465;
// 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
        $mail->FromName = $nick;
// smtp登录的账号 QQ邮箱即可
        $mail->Username = $user;
// smtp登录的密码 使用生成的授权码
        $mail->Password = $pass;
// 设置发件人邮箱地址 同登录账号
        $mail->From =$user;
// 邮件正文是否为html编码 注意此处是一个方法
        $mail->isHTML(true);
// 设置收件人邮箱地址
        if (is_array($address)){
            foreach ($address as $v){
                $mail->addAddress($v);
            }
        }else{
            $mail->addAddress($address);
        }
// 添加该邮件的主题
        $mail->Subject = $sub;
// 添加邮件正文
        $mail->Body =$content;
// 为该邮件添加附件
      //  $mail->addAttachment('./zhou.txt');
// 发送邮件 返回状态
        $status = $mail->send();
        if ($status) {
            return array("error"=>0);
        }else{
            return array("error"=>1,"message"=>$mail->ErrorInfo);
        }
    }

    /**
     * @param $txtfile
     * @return array|string
     * 逐行读取TXT文件
     */
    private function getTxtcontent($txtfile){
        $file = @fopen($txtfile,'r');
        $content = array();
        if(!$file){
            return 'file open fail';
        }else{
            $i = 0;
            while (!feof($file)){
                $content[$i] = mb_convert_encoding(fgets($file),"UTF-8","GBK,ASCII,ANSI,UTF-8");
                $i++ ;
            }
            fclose($file);
            $content = $this->array_remove_empty($content); //数组去空
        }
        $str=@implode(",",$content);
        return $str;
    }



    /**
     * 方法库-数组去除空值
     * @param string $num  数值
     * @return string
     */
    private function array_remove_empty(&$arr, $trim = true) {
        if (!is_array($arr)) return false;
        foreach($arr as $key => $value){
            if (is_array($value)) {
                self::array_remove_empty($arr[$key]);
            } else {
                $value = ($trim == true) ? trim($value) : $value;
                if (empty($value) || $value=="") {
                    unset($arr[$key]);
                } else {
                    $arr[$key] = $value;
                }
            }
        }
        return $arr;
    }



    /**
     * 上传文件
     */
    public function fileuploadAction(){
        $root_url =  'uploadfiles/maile/';
        //p($_FILES);
        if (!is_uploaded_file($_FILES['file']['tmp_name']))
            return array('code'=>0,'msg'=>'文件错误');
        $root_url.=date('Ymd').'/';
        if (!is_dir($root_url)) {
            mkdir($root_url,0777, true);
        }
        $ext = pathinfo($_FILES['file']['name']);
        $num="txt_";
        $pa=file_list::get_file_list($root_url);
        $na=count($pa) + 1;
        if ($na<10){
            $name=$num.'000'.$na;
        }elseif($na<100){
            $name=$num.'00'.$na;
        }elseif($na<1000){
            $name=$num.'0'.$na;
        }else{
            $name=$num.$na;
        }
        $n=$root_url.$name.".".$ext['extension'];
        $result=move_uploaded_file($_FILES['file']['tmp_name'],$n);
        if ($result){
            $str=$this->getTxtcontent($n);
           exit(json_encode(array('code'=>200,'msg'=>'导入成功','path'=>$n,'str'=>$str)));
        }else{
            exit(json_encode(array('code'=>0,'msg'=>'导入失败')));
        }
    }



}

4、前端页面代码。

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
		<title></title>
		<script src="{SITE_THEME}dan/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="{SITE_THEME}dan/layui/layui.js" type="text/javascript" charset="utf-8"></script>
		<link rel="stylesheet" type="text/css" href="{SITE_THEME}dan/layui/css/layui.css" />
		
	</head>

	<body>

		<div style="padding: 20px; background-color: #F2F2F2;">
			<div class="layui-row layui-col-space15">

				<form class="layui-form" action="">

					<div class="layui-col-md8 layui-col-md-offset2">

						<!--<div class="layui-card">
							<img src="{SITE_THEME}fenxi/plan/head.png" style="margin: 0; width: 100%; " />
						</div>
-->
						<div class="layui-card">
							<div class="layui-card-header" style="background-color: rgb(190,26,33); color: white;">邮箱批量发送</div>
							<div class="layui-card-body">
								<form class="layui-form" action="" lay-filter="component-form-element">
									<div class="layui-row layui-col-space10 layui-form-item">

										<div class="layui-form-item ">
											<label class="layui-form-label">登录账号:</label>
											<div class="layui-input-inline">
												<input type="text" name="username" lay-verify="required|email" value="" autocomplete="off" class="layui-input">
											</div>
											  <div class="layui-form-mid layui-word-aux">QQ邮箱设权登录账号</div>
										</div>
										<div class="layui-form-item ">
											<label class="layui-form-label">登录密码:</label>
											<div class="layui-input-inline">
												<input type="password" name="password" lay-verify="required" value="" autocomplete="off" class="layui-input">
											</div>
											  <div class="layui-form-mid layui-word-aux">授权登录的密码</div>
											
										</div>
										<div class="layui-form-item ">
											<label class="layui-form-label">SMPT:</label>
											<div class="layui-input-inline">
												<input type="text" readonly="" value="smtp.qq.com" autocomplete="off" class="layui-input">
											</div>
											  <div class="layui-form-mid layui-word-aux">qq域名邮箱的服务器地址(默认,无法更改)</div>
											
										</div>
										<div class="layui-form-item ">
											<label class="layui-form-label">昵称:</label>
											<div class="layui-input-inline">
												<input type="text" name="nickname" lay-verify="required" value="" autocomplete="off" class="layui-input">
											</div>
											  <div class="layui-form-mid layui-word-aux">发件人的昵称</div>
											
										</div>
										<div class="layui-form-item ">
											<label class="layui-form-label">邮件标题:</label>
											<div class="layui-input-block">
												<input type="text" name="subject" lay-verify="required" placeholder="请填写邮件标题" autocomplete="off" class="layui-input">
											</div>
											
										</div>
										
									<div class="layui-form-item">
										<label class="layui-form-label">邮件内容:</label>
										<div class="layui-input-block">
											   <textarea class="layui-textarea" name="content" placeholder="邮件内容必须填写" lay-verify="content"   id="LAY_demo1" ></textarea>
									
										</div>
									</div>
									
									 <div class="layui-form-item">
                                    <label class="layui-form-label">导入邮箱:</label>
                                  
                                    <button style="" type="button" class="layui-btn" id="test3">上传</button>&nbsp;&nbsp;&nbsp;
                                    <font color="red">注释:每个邮箱一行(少量不必导入)</font>
                                    <div class="layui-form-mid layui-word-aux">*只允许上传TXT文件</div>
                                
                                </div>

									<div class="layui-form-item">
										<label class="layui-form-label">邮箱:</label>
										<div class="layui-input-block">
											<textarea name="maile" id="xin" class="layui-textarea" lay-verify="required" placeholder="多个邮箱用英文,隔开"></textarea>
										</div>
										
									</div>
									
									
									
									<div class="layui-form-item">
										<div class="layui-input-block">
											<button class="layui-btn" lay-submit="" lay-filter="demo1" >立即发送</button>
											<button type="reset" class="layui-btn layui-btn-primary">重置</button>
										</div>
									</div>
									
									
								</form>
							</div>
						</div>

					<!--	<div class="layui-card">
							<img src="{SITE_THEME}lun/plan/foot.png" style="margin: 0; width: 100%; " />
						</div>-->

					</div>
				</form>

			</div>
		</div>

		
		<script type="text/javascript">
			layui.use(['form', 'element', 'layer', 'layedit','upload'], function() {
				var element = layui.element;
				var layer = layui.layer;
				var form = layui.form;
				var jq = layui.$;
				 var layedit=layui.layedit;
			    var upload=layui.upload;
				form.render();



 //自定义工具栏
            var demo1s= layedit.build('LAY_demo1', {
                tool: ['strong','italic','underline','del','link', 'unlink', '|', 'left', 'center', 'right']
                ,height: 150
            });

         
            //自定义验证规则
            form.verify({
                content: function(value){
                    layedit.sync(demo1s);
                },
             

            });



  //指定允许上传的文件类型
            upload.render({
                elem: '#test3'
                ,url: "{url('maile/fileupload')}"
                ,accept: 'file' //普通文件
                ,exts: 'txt'
                , before: function (input) {
                    loading = layer.load(2, {
                        shade: [0.2, '#000'] //0.2透明度的白色背景
                    });
                }
                ,done: function(res){
                    layer.close(loading);
                    if (res.code==200) {
                        layer.msg(res.msg, {icon: 1, time: 1000},function () {
                            jq("#xin").val(res.str);
                        });
                    }else {
                        layer.msg(res.msg, {icon: 2, time: 1000});
                    }
                    //console.log(res)
                }
                , error: function () {
                    layer.close(loading);
                    layer.msg('网络错误',{icon:2,time:1500});
                }
            });



				//监听提交
				form.on('submit(demo1)', function(data) {
					loading = layer.load(2, {
						shade: [0.2, '#000'] //0.2透明度的白色背景
					});
					var param = data.field;
					//console.log(param);
					jq.post(
						"{url('maile/index')}",
						param,
						function(data) {
							if(data.status == 1) {
								layer.close(loading);
								layer.msg(data.info, {
									icon: 1,
									time: 1500
								}, function() {
									location.reload();
								});
							} else {
								layer.close(loading);
								layer.msg(data.info, {
									icon: 2,
									anim: 6,
									time: 3000
								});
							}
						}).error(function() {
						layer.close(loading);
						layer.msg('服务器错误', {
							icon: 2,
							anim: 6,
							time: 1500
						});
					});
					return false;
				});

			});
		</script>

	</body>

</html>

5、页面效果图。

php 结合 PHPMailer 批量发送邮件。 (https://mushiming.com/)  第1张
发送邮件界面

6、发送成功。

php 结合 PHPMailer 批量发送邮件。 (https://mushiming.com/)  第2张

 

                                                                                                                         有任何问题欢迎留言: jackhhy520@qq.com

THE END

发表回复