<?php
namespace model;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use \model;
/**
 * Class email
 * @package model
 */
class email extends model
{
	/**
	  * @method 发送邮件
	  * @param  ema_to_email       string [必填] 接收人手机号码，多个逗号分隔
	  * @param  ema_title          string [必填] 标题
	  * @param  ema_text           string [必填] 内容
	  * @param  ema_from_email     string [可选] 发送人邮箱
	  * @param  ema_from_name      string [可选] 发送人
	  * @param  attachments        array [可选] 附件, [ 'path/filename'=>'showname',... ] 
	  */
	public function send($ema_to_email, $ema_title, $ema_text, $ema_from_email = '', $ema_from_name = '',$attachments=[])
	{	
	    //set_time_limit(120);
	    //dd($ema_to_email, $ema_title, $ema_text, $ema_from_email, $ema_from_nam,\mvc::$cfg['mailSendServer']);
		if(empty(\mvc::$cfg['mailSendServer'])) {
		    exitJson('邮件配置mailSendServer缺失');
		}
		$Account = \mvc::$cfg['mailSendServer'];
		$mail = new PHPMailer(true);
		try {
			if($Account['smtp'])$mail->IsSMTP(); 
			//Server settings
			$mail->SMTPDebug = false;                      //Enable verbose debug output
			$mail->CharSet='UTF-8';
			$mail->SMTPAuth = true; //开启认证 
			$mail->isSMTP();                                            //Send using SMTP
			$mail->Host       = $Account['server'];                     //Set the SMTP server to send through
			$mail->SMTPAuth   = true;                                   //Enable SMTP authentication
			$mail->Username   = $Account['username'];                     //SMTP username
			$mail->Password   = $Account['password'];                               //SMTP password
			//$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
			//腾讯企业邮箱不需要端口
			if(stripos($mail->Host, 'exmail.qq.com') === false)
				$mail->Port       = $Account['port'];                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

			if(empty($ema_from_email))
			$ema_from_email = $Account['defaultMail'];
			if(empty($ema_from_email)) 
				$ema_from_email = $Account['username'];
			$mail->From = $ema_from_email;

			if(empty($ema_from_name))
				$ema_from_name = LANG && LANG == 'en'? $Account['defaultCnName']: $Account['defaultEnName'];
			$mail->FromName = $ema_from_name;
			foreach(explode(',', $ema_to_email) as $SVV)
			{
				$mail->AddAddress($SVV); 
			}
			foreach($attachments as $k=>$v){
			    $mail->addAttachment($k, basename($v)); // 添加附件
			}
			$mail->Subject = $ema_title; 
			$mail->Body = $ema_text;
			$mail->IsHTML(true); 
			$mail->send();
			return ['ok'=>1];
		} catch (Exception $e) {
			return ['code'=>0, 'msg'=>$mail->ErrorInfo];
		}
	}
}